How to Convert a Unicode String to a Dictionary in Python?

Problem Formulation

Given a Unicode string representation of a dictionary. How to convert it to a dictionary?

Input:
u"{'a': 1, 'b': 2, 'c': 3}"

Output: 
{'a': 1, 'b': 2, 'c': 3}

Note: The u'string' representation represents a Unicode string that was introduced in Python 3. This is redundant as all strings in Python 3 are Unicode strings.

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 Unicode string contains a textual representation of a dictionary, the return value is a normal Python dictionary. This way, you can easily convert a Unicode string to a Python dictionary by means of the eval() function.

s = u"{'a': 1, 'b': 2, 'c': 3}"

d = eval(s)

print(d)
print(type(d))

The output is:

{'a': 1, 'b': 2, 'c': 3}
<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 containing a Python literal such as a Unicode string. It is also suitable for strings that potentially come from untrusted sources resolving many of the security concerns of the eval() method.

import ast

s = u"{'a': 1, 'b': 2, 'c': 3}"
d = ast.literal_eval(s)

print(d)
print(type(d))

The output is:

{'a': 1, 'b': 2, 'c': 3}
<class 'dict'>

Method 3: json.loads() & s.replace()

To convert a Unicode string representation of a dict to a dict, use the json.loads() method on the string. However, the JSON library requires you to first replace all single quote characters with escaped double-quote characters using the expression s.replace("'", "\""). In other words, the expression json.loads(s.replace("'", "\"")) converts the Unicode string s to a dictionary.

import json

s = u"{'a': 1, 'b': 2, 'c': 3}"

d = json.loads(s.replace("'", "\""))

print(d)
print(type(d))

The output is:

{'a': 1, 'b': 2, 'c': 3}
<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 Unicode string to a dictionary by splitting the string representation into a series of dictionary elements, and iteratively adding them element-wise to an initially empty dictionary.

Here’s an implementation in bare Python:

s = u"{'a': 1, 'b': 2, 'c': 'hello'            }"

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:

{'a': 1, 'b': 2, 'c': 3}
<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!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!