Skip to content
Related Articles

Related Articles

Python program to create a dictionary from a string

Improve Article
Save Article
Like Article
  • Last Updated : 21 Jun, 2020

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


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.




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


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




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)


Output:

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!