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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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'])

chevron_right


Output:

{'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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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'])

chevron_right


Output:

{'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

filter_none

edit
close

play_arrow

link
brightness_4
code

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)

chevron_right


Output:

{'13': 15, '12': 14, '11': 13}


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.