Python program to create Dictionary from String

How to create dictionary from String?

  • Split the string on ':' symbol, or on separator.
  • Every odd number element in resulting list will be key and even number element will be value.
  • You can get the keys and values easily with step parameter in range() function.
  • There are numerous options then to create dictionary, one is to simply use {K:v for k,v in zip(keys, values)}.
  • Alternative and very simple solution would be to use eval() function to create dictionary from string in python.

To convert a dictionary from string which contains keys and values there are two methods.

  1. eval() method
  2. using split() method

1. eval() method

eval() method takes in string which is in form of dictionary and converts it into dict object.


string = "{'a':1, 'b':2, 'c':3}"

Dictionary = eval(string)
print(Dictionary) 
print(Dictionary['a']) 

Output:

1

2. split() method

In this method, we split the key value pair first on comma, then we split the key value pair to separate key and value bny using '-' as separator and create tuple of two elements viz. key and value.

Pass this to dict() function to create a dictionary from string.

That's how you create a dictionary from string by using split() method.

string = "a - 1, b - 2, c - 3"
  
Dictionary = dict((e1.strip(), e2.strip())
             for e1, e2 in (element.split('-')  
             for element in string.split(', '))) 
  
print(Dictionary) 
print(Dictionary['a']) 
print(Dictionary['b'])

Output:

{'a': '1', 'b': '2', 'c': '3'}
1
2

If you want any particular solution regarding your problem, please comment down below. An Immediate response will be given to solve your problem.

Comments