
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to convert a string to 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:
>>>import ast >>>x = ast.literal_eval("{'foo' : 'bar', 'hello' : 'world'}") >>>type(x) <type'dict'>
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 Articles
- Convert string dictionary to dictionary in Python
- How to convert a String representation of a Dictionary to a dictionary in Python?
- How to convert the string representation of a dictionary to a dictionary in python?
- How to convert Javascript dictionary to Python dictionary?
- How to convert a JSON string to a dictionary in Swift?
- How to convert Python Dictionary to a list?
- How to convert a spreadsheet to Python dictionary?
- How to convert list to dictionary in Python?
- Convert byteString key:value pair of dictionary to String in Python
- Convert dictionary object into string in Python
- How to convert a dictionary to a matrix or nArray in Python?
- How to convert Python dictionary keys/values to lowercase?
- How can I convert a Python Named tuple to a dictionary?
- How to translate a python string according a given dictionary?
- Convert dictionary to list of tuples in Python

Advertisements