In Python, the conversion of different data types is a common problem and it is very important to do it right. Dictionary is the data type that saves the information/elements in a pair form. It is important to convert the string data type to a dictionary data type during programming. However, before going to the methods of conversion, let me explain the strings and dictionaries.
A string is a series of elements in Python. It is unchangeable. The elements or items are enclosed in single and double quotation marks. Since Python has no proper character data type. However, any character is also taken as a string in Python.
In Python, a dictionary is essentially a collection of changeable data items. This collection is present in an unordered form. Dictionaries save the data in which every element is in the form of a pair. The elements inside the brackets are present in the form of pairs and each pair is segregated by the comma. But the elements are isolated by using a colon.
The main attribute of the dictionary is that it does not accept polymorphism. We can get the data from the dictionary later by referencing the appropriate key name. Let’s discuss the techniques of converting the string to a dictionary.
Use json.loads () Method
In Python, the string is converted into a dictionary by the use of json.load () function. It is the built-in function. We must import this library by utilizing the “import” word before this function. For the implementation, we use the ‘spyder’ software version 5. For a new project, we create a new file by pressing the ‘new file’ option from the menu bar. Now, let’s start coding.
We initialized the string to be converted. The variable used for initializing is ‘string’. Here we take the names of different birds in a string. Then we call the print statement to return the names of the birds.
import json
# initialising the string
string ='{"bird1": "Pigeon", "bird2": "Peacock", "bird3": "Eagle", "bird4": "Dove"}'
print("String is", string)
# using.json.loads()
res_dict = json.loads(string)
# printing converted dictionary
print("The resultant dictionary is", res_dict)
We apply the json.load () function. This function contains a parameter. The variable ‘string’ is passed as a parameter of this function. In the last, the print statement returns the final dictionary after conversion. Now, we have to run this code. We tap the ‘run’ option from the menu bar of spyder.
The first print statement returns the names of 4 birds. This string is converted to a dictionary by using the json.load () function. And we get the resultant dictionary at the end.
Use ast.literal.eval () Method
Another function used for converting the string to the dictionary is ast.literal.eval (). It is also a built-in function. The conversion that happens by this method is effective. Before using this function, we must import the ‘ast’ library.
In this instance, we import the’ ast’ library to apply the ast.literal_eval () function. We take a string named ‘str1’. We initialize this string by the names of games. Here, we take only three games. We call the print statement to print the names of games.
#using ast()
import ast
#initialising the string
str1='{"game1":"Cricket", "game2":"football", "game3":"badminton"}'
print("String is ", str1)
#using ast.literal_eval
res_dict=ast.literal_eval(str1)
#printing converted dictionary
print("The resultant dictionary is·",res_dict)
The ast.literal_eval () has one parameter. So, we pass the given string as a parameter of the function. In the final step, we again call the print statement. It returns the final result.
We get the converted string by use of ast.literal_eval () method. In the end, the defined string in which we mention the names of birds is converted to the dictionary.
Use Generator Expression
This is another method to convert the string to a dictionary. In this method, we declare the elements of the string that makes a pair by the use of a hyphen or segregated by the use of a comma. Next, in for loop, we utilize the strip () function and split () function. These functions of string manipulation obtain the dictionary. By using the strip () function, we eliminate the spaces in between the elements of the string. This technique is not very effective at converting the strings, because it takes a long time to obtain the result.
In this instance, first, we declare the string in which we take the marks of different students in the same subject. The values of the string pair to each other with the help of a hyphen. Each pair of the string is separated with the help of a comma. This is important because it is a tool for getting the output that we need. Then, we call the print statement which returns the original value of the string.
# using generator expressions
# initialising the string
string = "Amna - 80, Sara 100, Javed - 65, Saim - 93, Bilal - 100"
print("String is ", string)
# using strip() and split()
res_dict = dict((a.strip(), int(b.strip()))
for a, b in (element.split('-')
for element in string.split(', ')))
# printing converted dictionary
print("The resultant dictionary is: ", res_dict)
print(type(res_dict))
In for loop, we use strip () function and split () function. By these functions, we obtain the values of the dictionary in a normal format. The strip () function removes the spaces in between the elements of the string. In the last, we printed the created dictionary and confirmed the type of dictionary with type ().
Now, we get the converted dictionary in a normal format by using generator expressions. At last, we also print the type of the resultant dictionary by the use of type ().
Conclusion
In this article, we explained various approaches of how to convert a string to a dictionary. The dictionaries are helpful data types. Sometimes, we face problems when we convert the strings to dictionaries. In Python, the string data type and dictionary data type have their significance. However, when the sharing of data happens across the network, it is mandatory to change the string to a dictionary to enable error-free transmission of data.