

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 the string representation of a dictionary to a dictionary in python?
We can use ast.literal_eval() here to evaluate the string as a python expression. It safely evaluates an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. For example:
s = "{'baz' : 'lol', 'foo' : 'bar'}" import ast s = ast.literal_eval(s) print s['foo'], s['baz']
This will give us the output:
bar lol
Dictionaries can also be seen as JSON strings. Thus we can use the json module to convert a string to dict as well. For example,
>>> import json >>> x = json.loads("{'foo' : 'bar', 'hello' : 'world'}") >>> type(x) <type 'dict'>
- Related Questions & Answers
- How to convert a String representation of a Dictionary to a dictionary in Python?
- Convert string dictionary to dictionary in Python
- How to convert a string to dictionary in Python?
- How to convert Javascript dictionary to Python dictionary?
- How to convert Python Dictionary to a list?
- How to convert a spreadsheet to Python dictionary?
- How to define a Python dictionary within dictionary?
- Convert byteString key:value pair of dictionary to String in Python
- Python - Convert a set into dictionary
- Convert dictionary object into string in Python
- Python - Convert flattened dictionary into nested dictionary
- Python Convert nested dictionary into flattened dictionary?
- How do I serialize a Python dictionary into a string, and then back to a dictionary?
- How to convert list to dictionary in Python?
- How to translate a python string according a given dictionary?
Advertisements