Hướng dẫn string to dict python

Converting one data type into another is a frequent problem in python programming and it is essential to deal with it properly. Dictionary is one of the data types in python which stores the data as a key-value pair. However, the exchange of data between the server and client is done by python json which is in string format by default.

As it is necessary to convert the python string to dictionary while programming, we have presented a detailed guide with different approaches to making this conversation effective and efficient. But before jumping on the methods, let us quickly recall python string and dictionary in detail.

What is Strings in Python?

Python string is an immutable collection of data elements. It is a sequence of Unicode characters wrapped inside the single and double-quotes. Python does not have a character data type and therefore the single character is simply considered as a string of length 1. To know more about the string data type, please refer to our article "4 Ways to Convert List to String in Python".

Check out the below example for a better understanding of strings in python

For Example

a = "Python Programming is Fun"
print(a) 

Output

Python Programming is Fun

What is Dictionary in Python?

A dictionary is an unordered collection of data elements that is mutable in nature. Python dictionary stores the data in the form of key-value pair.

Hence we can say that dictionaries are enclosed within the curly brackets including the key-value pairs separated by commas. The key and value are separated by the colon between them.

The most important feature of the python dictionaries is that they don’t allow polymorphism. Also, the keys in the dictionary are case-sensitive. Therefore, the uppercase and lowercase keys are considered different from each other. Later, you can access the dictionary data by referring to its corresponding key name.

Check out the below example for a better understanding of dictionaries in python.

For Example

sample_dict = {
  "vegetable": "carrot",
  "fruit": "orange",
  "chocolate": "kitkat"
}
print(sample_dict)

Output

{'vegetable': 'carrot', 'fruit': 'orange', 'chocolate': 'kitkat'}

Convert String to Dict in Python

Below are 3 methods to convert string to the dictionary in python:

1) Using json.loads()

You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.

The below example shows the brief working of json.loads() method:

For Example

import json
original_string = '{"John" : 01, "Rick" : 02, "Sam" : 03}' 
  
# printing original string 
print("The original string is : " + str(original_string))
  
# using json.loads() method
result = json.loads(original_string)
  
# print result
print("The converted dictionary is  : " + str(result))

Output

The original string is : {"John" : 01, "Rick" : 02, "Sam" : 03}
The converted dictionary is : {'John': 01, 'Rick': 02, 'Sam': 03}

2) Using ast.literal.eval()

The ast.literal.eval() is an inbuilt python library function used to convert string to dictionary efficiently. For this approach, you have to import the ast package from the python library and then use it with the literal_eval() method.

Check out the below example to understand the working of ast.literal.eval() method.

For Example

import ast
original_String = '{"John" : 01, "Rick" : 02, "Sam" : 03}'

# printing original string
print("The original string is : " + str(original_String))

# using ast.literal_eval() method
result = ast.literal_eval(original_String)

# print result
print("The converted dictionary is : " + str(result))

Output

The original string is : {"John" : 01, "Rick" : 02, "Sam" : 03}
The converted dictionary is : {'John': 01, 'Rick': 02, 'Sam': 03}

3) Using generator expression

In this method, we will first declare the string values paired with the hyphen or separated by a comma. Later we will use the strip() and split() method of string manipulation in the for loop to get the dictionary in the usual format. Strip() method will help us to remove the whitespace from the strings. This method is not as efficient for the conversion of string to dictionary as it requires a lot of time to get the output.

Check out the below example for the string to dictionary conversion using a generator expression

For Example

original_String = "John - 10 , Rick - 20, Sam - 30"  
print("The original string is ",original_String)  

#using strip() and split()  methods
result = dict((a.strip(), int(b.strip()))  
                     for a, b in (element.split('-')  
                                  for element in original_String.split(', ')))  
#printing converted dictionary  
print("The resultant dictionary is: ", result)  

Output

The original string is  John - 10 , Rick - 20, Sam - 30
The resultant dictionary is:  {'John': 10, 'Rick': 20, 'Sam': 30}

Conclusion

String and dictionary data type has its own importance when it comes to programming in python. But when we wish to share the data over the network as a client-server connection, it is very important to convert a string into the dictionary for error-free data transfer. We have mentioned the three common methods to explicitly convert the string into a dictionary which will help you to make your programming faster and efficient. To learn more about dictionary and JSON in python, check our detailed guide on “5 Ways to Convert Dictionary to JSON in Python”.