
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
# 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.
- Related Articles
- Python Program – Create dictionary from the list
- How to create a Pandas series from a python dictionary?
- How to create a Python dictionary from text file?
- C++ Program to Create a Dictionary with a Dictionary Literal
- Python Program to remove duplicate elements from a dictionary
- Program to create a lexically minimal string from two strings in python
- How to create a dictionary in Python?
- How to create Python dictionary from the value of another dictionary?
- Python – Create dictionary from the list
- How to create Python dictionary from JSON input?
- How to create a Python dictionary from an object's fields?
- How to convert a String representation of a Dictionary to a dictionary in Python?
- Python Program to Form a Dictionary from an Object of a Class
- Java Program to create a boolean variable from string
- How we can create a dictionary from a given tuple in Python?

Advertisements