Python program to create a dictionary from a string

In this article, we will learn different methods to convert a string into a dictionary in Python. This is useful when you have string data that represents key-value pairs and need to work with it as a dictionary.

Problem statement ? We are given a string input and need to convert it into a dictionary type.

Here we will discuss three methods to solve this problem, each suitable for different string formats.

Method 1 ? Using eval() Function

The eval() method works when the string syntax already resembles a dictionary format with curly braces, quotes, and colons. This method directly evaluates the string as Python code ?

Example

# String in dictionary format
string = "{'T':1, 'U':2, 'O':4, 'R':5}"

# Using eval() function
dict_string = eval(string)
print("Dictionary:", dict_string)
print("Value of 'T':", dict_string['T'])
print("Type:", type(dict_string))
Dictionary: {'T': 1, 'U': 2, 'O': 4, 'R': 5}
Value of 'T': 1
Type: <class 'dict'>

Note: Use eval() carefully as it can execute arbitrary code and pose security risks with untrusted input.

Method 2 ? Using Generator Expression

For strings with custom delimiters like dashes and commas, we can use generator expressions with split() to parse and create the dictionary ?

Example

# String with custom format
string = "T-3, U-2, O-4, R-5"

# Converting string to dictionary using generator
dict_string = dict((x.strip(), y.strip()) 
                   for x, y in (element.split('-') 
                   for element in string.split(', ')))

print("Dictionary:", dict_string)
print("Value of 'T':", dict_string['T'])
print("All keys:", list(dict_string.keys()))
Dictionary: {'T': '3', 'U': '2', 'O': '4', 'R': '5'}
Value of 'T': 3
All keys: ['T', 'U', 'O', 'R']

Method 3 ? Using json.loads() for JSON Strings

When the string is in JSON format, json.loads() is the safest and most reliable method ?

Example

import json

# JSON formatted string
json_string = '{"name": "Alice", "age": 25, "city": "New York"}'

# Converting JSON string to dictionary
dict_from_json = json.loads(json_string)
print("Dictionary:", dict_from_json)
print("Name:", dict_from_json['name'])
print("Age:", dict_from_json['age'])
Dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York'}
Name: Alice
Age: 25

Comparison

Method String Format Security Best For
eval() Python dict syntax Risky Trusted input only
Generator expression Custom delimiters Safe Custom formats
json.loads() JSON format Safe JSON strings

Conclusion

Use json.loads() for JSON-formatted strings, generator expressions for custom delimited formats, and avoid eval() unless you completely trust the input source. Choose the method based on your string format and security requirements.

Updated on: 2026-03-25T07:00:58+05:30

716 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements