convert string representation of dictionary to dictionary

Python – Convert Dictionary String to Dictionary

In this tutorial, we will look at how to convert the string representation of a dictionary to a dictionary in Python.

convert string representation of dictionary to dictionary

You can use the ast.literal_eval() function to convert the string representation of a dictionary to a dictionary in Python. The following is the syntax.

import ast

# convert string representation of dict to dict
ast.literal_eval(s)

It returns a dictionary.

Let’s look at an example –

import ast

# string representation of a dictionary
s = '{"Name": "Clint Barton", "Age": 47, "Team": "Avengers", "Skills": "Archery"}'
# convert s to dict
d = ast.literal_eval(s)
# display d and its type
print(d)
print(type(d))

Output:

{'Name': 'Clint Barton', 'Age': 47, 'Team': 'Avengers', 'Skills': 'Archery'}
<class 'dict'>

We get the result as a dictionary.

Alternatively, you can use the json.loads() function to convert a string representation of a dictionary to a dictionary in Python.

Let’s use this function on the above example –

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

import json

# string representation of a dictionary
s = '{"Name": "Clint Barton", "Age": 47, "Team": "Avengers", "Skills": "Archery"}'
# convert s to dict
d = json.loads(s)
# display d and its type
print(d)
print(type(d))

Output:

{'Name': 'Clint Barton', 'Age': 47, 'Team': 'Avengers', 'Skills': 'Archery'}
<class 'dict'>

We get the same result as above, a dictionary.

Note that the json.loads() function will only work on valid JSON strings. For example, if your string contains keys or values in single quotes, or if it has trailing commas, etc. this method will not work.

import json

# string representation of a dictionary
s = "{'Name': 'Clint Barton', 'Age': 47, 'Team': 'Avengers', 'Skills': 'Archery'}"
# convert s to dict
d = json.loads(s)
# display d and its type
print(d)
print(type(d))

Output:

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7144/4188743168.py in <module>
      4 s = "{'Name': 'Clint Barton', 'Age': 47, 'Team': 'Avengers', 'Skills': 'Archery'}"
      5 # convert s to dict
----> 6 d = json.loads(s)
      7 # display d and its type
      8 print(d)
...
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

We get a “JSONDecodeError”. This happened because the string s here contains the keys and values in single quotes.

For more on JSON, refer to this guide.

But, if you use the ast.literal_eval() function on the string above, it will correctly convert it to a dictionary.

import ast

# string representation of a dictionary
s = "{'Name': 'Clint Barton', 'Age': 47, 'Team': 'Avengers', 'Skills': 'Archery'}"
# convert s to dict
d = ast.literal_eval(s)
# display d and its type
print(d)
print(type(d))

Output:

{'Name': 'Clint Barton', 'Age': 47, 'Team': 'Avengers', 'Skills': 'Archery'}
<class 'dict'>

We get the result without any errors with ast.literal_eval(). Generally, using this method is more stable than json.loads() for converting dictionary string to a dictionary in Python.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top