
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Convert String Representation of a Dictionary to Dictionary in Python
To convert a string represented dictionary to an original dictionary we can use built-in functions like eval(), json.load(), and ast.literal_eval(). Initially, we must ensure that the string contains a valid representation of the dictionary. Let's discuss how each function will convert the string representation of a dictionary to an original dictionary.
Using the eval() function
The eval() is a python built-In function that takes a string argument, parses it as a code expression, and evaluates the expression. If the input expression contains a string representation of a dictionary, then the eval() method returns it as a normal Python dictionary.
Syntax
eval(expression[, globals[, locals]])
Parameters
expression:It takes a string then it will be parsed and evaluated as a Python expression.
globals:It is an optional parameter, used to specify the available global methods and variables.
locals:It is also an optional parameter, used to specify the available local methods and variables.
Return Value
Returns output of the expression.
Example
Using the eval() function is the easiest way but it is dangerous, because it may execute any malicious code injected inside the string.
String_dict = "{'1': 1, '2': 2, '3': 3}" print("Input string represented dictionary: ",String_dict) print(type(String_dict)) # use the eval method to convert the expression dict_ = eval(String_dict) print("Output: ", dict_) print(type(dict_))
Output
Input string represented dictionary: {'1': 1, '2': 2, '3': 3} <class 'str'> Output: {'1': 1, '2': 2, '3': 3} <class 'dict'>
Using the ast.literal_eval() function
Abstract Syntax Tree (ast) is a python module that provides a method called literal_eval(), which is used to convert string to dictionary efficiently.
The method never executes the code, it will parse the expression and return only if it is a literal, so it is the safest way to convert a string.
Syntax
ast.literal_eval ( node_or_string )
Example
Let us see an example of this function. To use the literal_eval() function, initially we need to import the ast package.
import ast string_dict = "{'a': 1, 'b': 2, 'c': 3}" print("Input string represented dictionary: ",string_dict) print(type(string_dict)) # convert the string dict_ = ast.literal_eval(string_dict) print("Output: ", dict_) print(type(dict_))
Output
Input string represented dictionary: {'a': 1, 'b': 2, 'c': 3} <class 'str'> Output: {'a': 1, 'b': 2, 'c': 3} <class 'dict'>
As we can see in above output The ast.literal_eval() method successfully evaluated the string, and returned the Python dictionary object.
Example
Following is another example
import ast stringA = '{"Mon" : 3, "Wed" : 5, "Fri" : 7}' # Given string dictionary print("Given string : \n",stringA) # using json.loads() res = ast.literal_eval(stringA) # Result print("The converted dictionary : \n",res)
Output
Running the above code gives us the following result
Given string : {"Mon" : 3, "Wed" : 5, "Fri" : 7} The converted dictionary : {'Mon': 3, 'Wed': 5, 'Fri': 7}
Using the json.loads() function
The json.loads() is a built-in Python function that converts a valid string to a python object. Let's use the json.loads() method to convert a string representation of a dictionary into an original dictionary object.
Syntax
json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Before using the loads() method, we need to import the json library first.
Example
In the following example we can see that the loads() function returned a dictionary, and we verified that by using the type() method.
import json d = '{"Age": 7, "Gender": "Female", "Name": "Jennifer"}' print("Input string represented dictionary: ",d) print(type(d)) python_dict = json.loads(d) print("Output: ", python_dict) print(type(python_dict))
Output
Input string represented dictionary: {"Age": 7, "Gender": "Female", "Name": "Jennifer"} <class 'str'> Output: {'Age': 7, 'Gender': 'Female', 'Name': 'Jennifer'} <class 'dict'>
Example
Following is another example of this function
import json stringA = '{"Mon" : 3, "Wed" : 5, "Fri" : 7}' # Given string dictionary print("Given string : \n",stringA) # using json.loads() res = json.loads(stringA) # Result print("The converted dictionary : \n",res)
Output
Running the above code gives us the following result
Given string : {"Mon" : 3, "Wed" : 5, "Fri" : 7} The converted dictionary : {'Mon': 3, 'Wed': 5, 'Fri': 7}
Note: json.loads() will raise an error if we have single quotes as a part of our keys or values.