String to Dictionary Python


In this tutorial, we will cover different ways to convert string to dictionary in Python.

Dictionary is one of the most commonly used data types in Python. It is an unordered collection of items of a key/value pair.

Most often, these dictionaries are stored as a string. For example, a dictionary can be stored as a string in JSON format.

To use them in Python, we first need to convert them into a dictionary. Luckily, Python provides us with multiple ways to do so.

Let's see how we can convert a string to a dictionary in Python.

String to Dictionary Python

1. String to Dictionary using json module

Python provides a built-in module called json to work with JSON data. This module has multiple methods to deal with JSON data.

One of the methods is loads() which is used to convert a string to a dictionary.

Start with importing the json module. Then, use the loads() method to convert the string to a dictionary.

Example
import json
str = '{"category": "programming", "book": "python"}'
d = json.loads(str)
print(d)
print(type(d))
{'category': 'programming', 'book': 'python'}
<class 'dict'>

2. String to Dictionary using ast.literal_eval()

Python has another module called ast that is used to work with Abstract Syntax Trees. This module has a method called literal_eval() that evaluates literal Python expressions and returns the value.

Means it can evaluate a string containing a Python expression and return the value.

Let's use this method to convert a string to a dictionary.

Example
import ast
str = '{"category": "programming", "book": "python"}'

d = ast.literal_eval(str)
print(d)
print(type(d))
{'category': 'programming', 'book': 'python'}
<class 'dict'>

Note: This method is not safe to use. It can evaluate any Python expression. So, it can be dangerous if you are using it with untrusted input.


3. String to Dictionary using eval() function

eval() is a built-in function in Python that can evaluate any Python expression given as a string.

Just like previous method, this method can also be used to convert a string to a dictionary.

Let's see how we can do it.

Example
str = '{"category": "programming", "book": "python"}'
          
d = eval(str)
print(d)
print(type(d))
{'category': 'programming', 'book': 'python'}
<class 'dict'>

Both ast.literal_eval() and eval() evaluates any Python expression given as string but ast.literal_eval() is limited evaluating only literal Python expressions.


4. Using Custom Function

Above we have looked at 3 different build-in methods to convert a string to a dictionary. But, if you want to use a custom function, you can do so.

Here is a custom function that can be used to convert a string to a dictionary.

Example
def string_to_dict(s):
    try:
        d = {}
        s = s.strip()
        if s[0] != '{' or s[-1] != '}':
            return None
        s = s[1:-1]
        key_value_pairs = s.split(',')
        for pair in key_value_pairs:
            key_value = pair.split(':')
            if len(key_value) != 2:
                return None
            key = key_value[0].strip()
            value = key_value[1].strip()
            if (key[0] == '"' and key[-1] == '"') or (key[0] == "'" and key[-1] == "'"):
                key = key[1:-1]
            if (value[0] == '"' and value[-1] == '"') or (value[0] == "'" and value[-1] == "'"):
                value = value[1:-1]
            d[key] = value
        return d
    except:
        return None

str = '{"category": "programming", "book": "python"}'
d = string_to_dict(str)
print(d)
print(type(d))
{'category': 'programming', 'book': 'python'}
<class 'dict'>

The above function converts a string to a dictionary in the following steps:

  • First, it checks if the string is a valid dictionary string. If not, it returns None.
  • Then, remove the curly braces from both ends
  • Splits the string into key-value pairs using split() method and loop through each pair.
  • Now split each pair into key and value
  • Finally, it adds the key-value pair to the dictionary.

Conclusion

We have seen 4 different ways to convert a string to a dictionary in Python. All the methods are explained with examples.

Among all the methods, json.loads() is the most popular and recommended method because it safely converts a string to a dictionary.

However, if you want to use a custom function, you can use the function we have created in this tutorial.

Now, it's your turn to use them for real world applications.

Happy Learning!😇