Python program to create a dictionary from a string


In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given a string input, we need to convert it into dictionary type

Here we will discuss two methods to solve the problem without using a built-in dict() function.

Method 1 − Using eval() method

Eval method is used only when the syntax or the formation of string resembles that of a dictionary. Direct conversion of string to the dictionary can happen in that case as discussed below.

Example

 Live Demo

# String
string = "{'T':1, 'U':2, 'T':3, 'O':4, 'R':5}"
# eval() function
dict_string = eval(string)
print(dict_string)
print(dict_string['T'])
print(dict_string['T'])

Output

{'T': 3, 'U': 2, 'O': 4, 'R': 5}
3
3

Method 2 − Using generator functions

If we get a string input that resembles the syntax of a dictionary then by the help of generator expressions we can convert it to a dictionary.

Example

 Live Demo

string = "T-3 , U-2 , T-1 , O-4 , R-5"
# Converting string to dictionary
dict_string = dict((x.strip(), y.strip()) for x, y in
(element.split('-') for element in string.split(', ')))
print(dict_string)
print(dict_string['T'])
print(dict_string['T'])

Output

{'T': '1', 'U': '2', 'O': '4', 'R': '5'}
1
1

Conclusion

In this article, we have learned how we can create a dictionary from a string.

Updated on: 11-Jul-2020

549 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements