- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert a String representation of a Dictionary to a dictionary in Python?
Dictionary object is easily convertible to string by str() function.
>>> D1={'1':1, '2':2, '3':3} >>> D1 {'1': 1, '2': 2, '3': 3} >>> str(D1) "{'1': 1, '2': 2, '3': 3}"
To convert a string to dictionary, we have to ensure that the string contains a valid representation of dictionary. This can be done by eval() function.
>>> D1={'1':1, '2':2, '3':3} >>> s=str(D1) >>> s "{'1': 1, '2': 2, '3': 3}" >>> D2=eval(s) >>> D2 {'1': 1, '2': 2, '3': 3}
Abstract Syntax Tree (ast) module of Python has literal_eval() method which safely evaluates valid Python literal structure.
>>> D1={'1':1, '2':2, '3':3} >>> s=str(D1) >>> import ast >>> D2=ast.literal_eval(s) >>> D2 {'1': 1, '2': 2, '3': 3}
- Related Articles
- How to convert the string representation of a dictionary to a dictionary in python?
- How to convert a string to dictionary in Python?
- Convert string dictionary to dictionary in Python
- How to convert a spreadsheet to Python dictionary?
- How to convert Python Dictionary to a list?
- How to convert Javascript dictionary to Python dictionary?
- How to define a Python dictionary within dictionary?
- How to convert a dictionary to a matrix or nArray in Python?
- How do I serialize a Python dictionary into a string, and then back to a dictionary?
- How to translate a python string according a given dictionary?
- Convert byteString key:value pair of dictionary to String in Python
- How can I convert a Python Named tuple to a dictionary?
- Python program to create a dictionary from a string
- Python - Convert a set into dictionary
- How to convert list to dictionary in Python?

Advertisements