Python program to create a dictionary from a string
Dictionary in python is a very useful data structure and at many times we see problems regarding converting a string to a dictionary.
So, let us discuss how we can tackle this problem.
Method # 1: Using eval()
If we get a string input which completely resembles a dictionary object(if the string looks like dictionary as in python) then we can easily convert it to dictionary using
eval() in Python.
# Python3 code to convert # a string to a dictionary # Initializing String string = "{'A':13, 'B':14, 'C':15}" # eval() convert string to dictionary Dict = eval(string) print(Dict) print(Dict['A']) print(Dict['C']) |
{'C': 15, 'B': 14, 'A': 13}
13
15
Method # 2: Using generator expressions in python
If we get a string input does not completely resemble a dictionary object then we can use generator expressions to convert it to a dictionary.
# Python3 code to convert # a string to a dictionary # Initializing String string = "A - 13, B - 14, C - 15" # Converting string to dictionary Dict = dict((x.strip(), y.strip()) for x, y in (element.split('-') for element in string.split(', '))) print(Dict) print(Dict['A']) print(Dict['C']) |
{'C': '15', 'A': '13', 'B': '14'}
13
15
The code given above does not convert integers to an int type,
if integers keys are there then just line 8 would work
string = "11 - 13, 12 - 14, 13 - 15" Dict = dict((x.strip(), int(y.strip())) for x, y in (element.split('-') for element in string.split(', '))) print(Dict) |
{'13': 15, '12': 14, '11': 13}
Recommended Posts:
- Python | Ways to create a dictionary of Lists
- Python | Create a dictionary using list with none values
- Python | Convert string dictionary to dictionary
- Python | Converting list string to dictionary
- Python | Convert dictionary object into string
- Python | Converting String content to dictionary
- Python Dictionary to find mirror characters in a string
- Find the first repeated word in a string in Python using Dictionary
- Python | Convert byteString key:value pair of dictionary to String
- Python program to find the sum of all items in a dictionary
- Python program to find second maximum value in Dictionary
- Python | Convert key-value pair comma separated string into dictionary
- Python program to Swap Keys and Values in Dictionary
- Python program to find the highest 3 values in a dictionary
- Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



