How to Convert a String Representation of a Dictionary to a Dictionary?

Problem: How to convert the str representation of a dict into a dict?

Example: Let’s create a list of NBA players. You have LeBron on there, Harden, Steph, and all the talented guys. Have it look just like this.

basketball = '{"LeBron James": "Los Angeles Lakers", "James Harden" : "Houston Rockets", "Stephen Curry" : "Golden State Warriors", "Trae Young" : "Atlanta Hawks", "Luka Doncic" : "Dallas Mavericks", "Giannis Antetokounmpo" : "Milwaukee Bucks", "Bradley Beal" : "Washington Wizards", "Anthony Davis" : "Los Angeles Lakers", "Kawhi Leonard" : "Los Angeles Clippers", "Jamal Murray" : "Denver Nuggets"}'

It looks like a dictionary, but it is not. It’s a string. How to change it from a string to a dictionary?

Solution Overview: You can do so by converting it to a dictionary. You could do it the long way by typing everything, but that would involve making some adjustments. Instead, there are a couple of ways you can do it and one big NO-NO that you shouldn’t use (Method 1):

Exercise: Run the code. Are all three variables of type dictionary?

Let’s start with the one you shouldn’t use.

Method 1: eval() is Dangerous

Python’s eval function is built-in and it can seem like a good idea for you to use. However, using the eval() function is dangerous because it can execute all kinds of Python code on your operating system like removing or creating files. You should never trust code from the internet that’s packed into an eval() or exec() function!

Ned Batchelder covers this topic well in his blog. Even with safeguards you put in, it might not be enough.

d = eval(basketball)

The eval() function evaluates the string and understands that it is a dictionary. So, it returns the dictionary. The result is stored in the variable d.

As you start working with Python more, you need to be careful not to use options like eval(). The fact is, there are better options for you to use. And there’s one easy alternative that can get you where you want.

Method 2: AST

AST is another built-in module for Python. There’s no need for you to install AST because it’s just there for you. Just import it at the top of your code using import ast. The library assists the Python interpreter in analyzing the Abstract Syntax Tree—what you may call the “grammar of your code“.

You’ll specifically need to use literal_eval (or ast.literal_eval). You can evaluate the string that contains a literal or container display. This works for all Python structures, including dictionaries.

d = ast.literal_eval(basketball)

For this instance, you would use it like this. Using this method allows you to convert your string into a dictionary.

If it helps any, you can always try to create a little comparison between the two. If you need more convincing, then create a print statement. Doing so will show that you have a class that is a dictionary. If it doesn’t, then you might want to check your code again.

print(type(d))

This is the most common solution to the problem—compare this article to learn more!

But if you’re looking for something different, then we have another option for you to consider.

Method 3: JSON

JSON stands for JavaScript Object Notation. It does use JavaScript syntax, but it’s used for more than just JavaScript.

Just like with AST, JSON is a built-in module for Python, which means you’ll never need to install it. All you have to do is enter import json at the top of your script.

For this example, we’ll be using the json.loads method, which is the equivalent of reading the file, or in this instance our soon-to-be dictionary.

Now you might be wondering why we wouldn’t use json.load. There’s a good reason for that. With the load function, it’s assuming you have a JSON file already setup. Using loads allows you to convert your string, in this instance, into a dictionary.

If you were to use json.load(), you would get an Attribute Error. Please add the “s” after load. You will thank us later.

d = json.loads(basketball)

For our example, we recommend turned it into a variable.

It’s that easy. When you run it, you’ll see that it turns into a Python dictionary. But how do you know if the conversion worked? Well, it’s similar to the previous method. You have a few options that you can turn to. But the best one by far is to use the type function. It’s just good to use. And like we mentioned above, you can do it as a way to compare both variables.

Now, how would you like to not only convert the string to a dictionary but write it to a JSON file? It is easy enough to do, especially if you’ve written files in Python before.

You’ll want to use a with open statement to write your JSON file using “w” for write. The only difference is what you would be writing in the next line. Instead of using write, you would use json.dump() as well as the variable and the outfile. It will look like this.

with open("players.json", "w") as f:
	json.dump(d, f)

When you’re done, it writes the complete JSON dictionary to your file. You can open it up and voila, it’s like magic.

Whatever the route you decide to go, you’ve got solutions available to you that can be helpful. And hey, we hope you learned something from this.