Problem Formulation
Given a string representation of a dictionary. How to convert it to a dictionary?
Input: '{"1": "hi", "2": "alice", "3": "python"}' Output: {'a': 1, 'b': 2, 'c': 3}
Method 1: eval()
The built-in eval()
function takes a string argument, parses it as if it was a code expression, and evaluates the expression. If the string contains a textual representation of a dictionary, the return value is a normal Python dictionary. This way, you can easily convert a string to a Python dictionary by means of the eval()
function.
s = '{"1": "hi", "2": "alice", "3": "python"}' d = eval(s) print(d) print(type(d))
The output is:
{'1': 'hi', '2': 'alice', '3': 'python'} <class 'dict'>
You can learn more about the built-in eval()
function in the following video:
Method 2: ast.literal_eval()
The ast.literal_eval()
method safely evaluates an expression or a string literal such as a dictionary represented by a string. It is also suitable for strings that potentially come from untrusted sources resolving many of the security concerns of the eval()
method. This way, you can convert a string representation s
of a dictionary by using the expression ast.literal_eval(s)
.
import ast s = '{"1": "hi", "2": "alice", "3": "python"}' d = ast.literal_eval(s) print(d) print(type(d))
The output is:
{'1': 'hi', '2': 'alice', '3': 'python'} <class 'dict'>
Method 3: json.loads() & s.replace()
To convert a string representation of a dict to a dict, use the json.loads()
method on the string. First, replace all single quote characters with escaped double-quote characters using the expression s.replace("'", """)
to make it work with the JSON library in Python. The expression json.loads(s.replace("'", """))
converts string s
to a dictionary.
import json s = '{"1": "hi", "2": "alice", "3": "python"}' d = json.loads(s.replace("'", """)) print(d) print(type(d))
The output is:
{'1': 'hi', '2': 'alice', '3': 'python'} <class 'dict'>
Unfortunately, this method is not optimal because it’ll fail for dictionary representations with trailing commas and single quotes as parts of dictionary keys or values. It’s also not the most simple one, so the general approach discussed in method 1 is preferred.
You can dive deeper into the string.replace()
method in the following video tutorial:
Method 4: Iterative Approach
You can also convert a string to a dictionary by splitting the string representation into a sequence of (key, value) pairs. Then, you can add each (key, value) pair to an initially empty dictionary after some housekeeping.
Here’s an implementation in bare Python:
s = '{"1": "hi", "2": "alice", "3": "python"}' def string_to_dict(s): new_dict = {} # Determine key, value pairs mappings = s.replace('{', '').replace('}', '').split(',') for x in mappings: key, value = x.split(':') # Automatically convert (key, value) pairs to correct type key, value = eval(key), eval(value) # Store (key, value) pair new_dict[key] = value return new_dict d = string_to_dict(s) print(d) print(type(d))
The output is:
{'1': 'hi', '2': 'alice', '3': 'python'} <class 'dict'>
You can learn more about string splitting in the following video tutorial:
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.