
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create a Dictionary from a String in Python
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
# 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
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.
Advertisements