You are currently viewing Convert String to Dictionary Python

How to convert string to the dictionary in Python? In Python, if you want to convert a string to a dictionary, you can do so using the json module. If the string is in JSON format, this module can easily convert it. Alternatively, if the string is formatted in a specific way, you can parse and process it manually. If you have a JSON string that represents a dictionary and you want to convert it back into a Python dictionary, the json module’s loads() function is the way to go. This function can take a JSON-formatted string and convert it into a Python dictionary.

Advertisements

You can convert string to the dictionary in Python using many ways, for example, by using json.loads(), ast.literal_eval(), eval(), replace(), split(), dictionary comprehension, and generator expression. In this article, I will explain how to convert a string to a dictionary by using all these functions with examples.

1. Quick Examples of Convert String to Dictionary

If you are in a hurry, below are some quick examples of converting string to the dictionary in Python.


# Quick examples of converting string to dictionary

import json
import ast

# Initializing string
string = '{"Python" : 2000, "Spark" : 3000, "Java" : 2500}'

# Example 1: Using json.loads()
# Convert the string to a dictionary 
result = json.loads(string)

# Example 2: Using ast.literal_eval() method
# Convert the string to a dictionary
result = ast.literal_eval(string)

# Example 3: Using eval() method
# Convert dictionary string to dictionary
result = eval(string)

# Example 4: Using eval() and replace() methods
# Convert dictionary string to dictionary
result = eval(string.replace("'", "\""))

# Example 5: Using the split() method and a dictionary comprehension 
def str_to_dict(string):
      string = string.strip('{}')
      pairs = string.split(', ')
      return {key[1:-2]: int(value) for key, value in (pair.split(': ') for pair in pairs)}    
result = str_to_dict(string)

# Example 6: Using generator expression
# Using strip() and split()  methods
string = "Python - 2000, Spark - 3000, Java - 2500"
result = dict((a.strip(), int(b.strip()))  
                     for a, b in (element.split('-')  
                                  for element in string.split(', '))) 

2. Convert String to Dictionary Using Python json

You can convert a string to a dictionary using the json.loads() function from the json module. This function parses a JSON-encoded string and returns a Python dictionary.

Make sure that the string you provide is properly formatted JSON. JSON uses double quotes for keys and string values, and the keys must be enclosed in double quotes. If the string is not valid JSON, the json.loads() function will raise a json.JSONDecodeError.


import json

# Initializing string
string = '{"Python" : 2000, "Spark" : 3000, "Java" : 2500}'
print("Original string:",string)

# Using json.loads()
# Convert the string to a dictionary 
result = json.loads(string)
print("After converting the string to a dictionary:",result)

Yields below output.

python convert string dictionary

In this program, the json.loads() function takes the JSON string as an argument and returns a Python dictionary. Just ensure that the input string is properly formatted JSON to avoid any parsing errors.

3. Convert String to Dictionary Using ast.literal_eval()

You can also use the ast.literal_eval() method to convert a string into a dictionary. For example, first, import the ast module. Define the string variable containing the dictionary as a string. Use ast.literal_eval(string) to parse the string and convert it into a dictionary.

Keep in mind that ast.literal_eval() is only suitable for evaluating simple and safe Python literals. It should not be used to evaluate arbitrary or potentially malicious code. For more complex expressions, using the json module is recommended.


import ast

# Initializing string
string = '{"Python" : 2000, "Spark" : 3000, "Java" : 2500}'
print("Original string:",string)

# Using ast.literal_eval() method
# Convert the string to a dictionary
result = ast.literal_eval(string)
print("After converting the string to a dictionary:",result)

Yields the same output as above.

4. Convert String to Dictionary Using eval() Method

To convert a string representation of a dictionary to an actual dictionary, use eval() function.

However, it’s important to note that using eval() can be risky if you’re working with untrusted input, as it can execute arbitrary code. It’s generally safer to use ast.literal_eval() specific parsing libraries json for these tasks.


# Initializing string
string = '{"Python" : 2000, "Spark" : 3000, "Java" : 2500}'
print("Original string:",string)

# Using eval() method
# Convert dictionary string to dictionary
result = eval(string)
print("After converting the string to a dictionary:",result)

Yields the same output as above.

5. Using eval() and replace() Methods

You can use the eval() function along with the str.replace() method to convert a string representing a dictionary into an actual dictionary.

In the below example, first, defines the string variable containing the dictionary as a string with single quotes for keys and values. Uses the replace() method to replace all single quotes (') with double quotes (") in the string. This step is necessary because JSON (and Python dictionaries) use double quotes for string representation. The modified string with double quotes is then passed to the eval() function to evaluate and convert it into a dictionary.


# initializing string
string = '{"Python" : 2000, "Spark" : 3000, "Java" : 2500}'
print("Original string:",string)

# Using eval() and replace() methods
# Convert dictionary string to dictionary
result = eval(string.replace("'", "\""))
print("After converting the string to a dictionary:",result)

Yields the same output as above.

6. Using split() Method and a Dictionary Comprehension

You can also use the split() method along with dictionary comprehension to convert a string representation of a dictionary into an actual dictionary.

In the below example, first, the str_to_dict() function is defined to process the input string. This function first removes the curly braces from the string using .strip('{}'). It then splits the remaining string into pairs using ',' as the delimiter. A dictionary comprehension is used to create a dictionary from each pair: The pair is split further into a key and a value is used ':' as the delimiter. The key is modified by removing the double quotes around it using slicing (key[1:-2]). The value is converted to an integer using int(). Finally, the str_to_dict() function is called with the input string, and the resulting dictionary is stored in the result variable.


# Initializing string
string = '{"Python" : 2000, "Spark" : 3000, "Java" : 2500}'
print("Original string:",string)

# Using the split() method and a dictionary comprehension 
def str_to_dict(string):
      string = string.strip('{}')
      pairs = string.split(', ')
      return {key[1:-2]: int(value) for key, value in (pair.split(': ') for pair in pairs)}    
result = str_to_dict(string)
print("After converting the string to a dictionary:", result)

Yields the same output as above.

7. Using Generator Expression

You can also use a generator expression with the strip() and split() methods to convert a string representation of a dictionary into an actual dictionary. This approach is suitable for scenarios where you have a specific delimiter (such as a hyphen) separating key-value pairs in the string.

In the below example, first, the split(', ') function is used to split the string into individual key-value pairs. A generator expression (element.split('-') for element in string.split(', ')) is used to split each pair into key and value elements by using the hyphen - as the delimiter. Inside the outer generator expression, the strip() method is used to remove any leading or trailing whitespace from each key and value. The inner generator expression produces pairs of stripped key and value elements. The outer generator expression generates these pairs and feeds them to the dict() constructor to create a dictionary.

Related: In Python split the string by delimiter or multiple delimiters.


# Initializing string
string = "Python - 2000, Spark - 3000, Java - 2500"
print("Original string:",string)

# Using generator expression
# Using strip() and split()  methods
result = dict((a.strip(), int(b.strip()))  
                     for a, b in (element.split('-')  
                                  for element in string.split(', '))) 
print("After converting the string to a dictionary:", result)

# Output:
# Original string: Python - 2000, Spark - 3000, Java - 2500
# After converting the string to a dictionary: {'Python': 2000, 'Spark': 3000, 'Java': 2500}

Conclusion

In this article, I have explained how to convert a string to a dictionary in Python by using json.loads(), ast.literal_eval(), eval(), replace(), split(), dictionary comprehension, and generator expression with examples.

Happy Learning !!