Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Converting list string to dictionary in Python
Sometimes you need to convert a string that looks like a list with key-value pairs into an actual Python dictionary. For example, converting '[Mon:3, Tue:5, Fri:11]' into {'Mon': '3', 'Tue': '5', 'Fri': '11'}. Python provides several approaches to handle this conversion.
Using split() and Dictionary Comprehension
This approach uses split() to separate elements and slicing to remove the brackets, then creates a dictionary using comprehension ?
string_data = '[Mon:3, Tue:5, Fri:11]'
# Given string
print("Given string:", string_data)
print("Type:", type(string_data))
# Using split and slicing
result = {sub.split(":")[0]: sub.split(":")[1] for sub in string_data[1:-1].split(", ")}
# Result
print("The converted dictionary:", result)
print("Type:", type(result))
Given string: [Mon:3, Tue:5, Fri:11]
Type: <class 'str'>
The converted dictionary: {'Mon': '3', 'Tue': '5', 'Fri': '11'}
Type: <class 'dict'>
Using eval() and replace()
The eval() function evaluates the string as Python code after replacing square brackets with curly braces to create dictionary syntax ?
string_data = '[18:3, 21:5, 34:11]'
# Given string
print("Given string:", string_data)
print("Type:", type(string_data))
# Using eval with replace
result = eval(string_data.replace("[", "{").replace("]", "}"))
# Result
print("The converted dictionary:", result)
print("Type:", type(result))
Given string: [18:3, 21:5, 34:11]
Type: <class 'str'>
The converted dictionary: {18: 3, 21: 5, 34: 11}
Type: <class 'dict'>
Using ast.literal_eval() (Safer Alternative)
For better security, use ast.literal_eval() instead of eval() as it only evaluates literal expressions ?
import ast
string_data = '[name:John, age:25, city:NYC]'
# Using ast.literal_eval with replace
try:
result = ast.literal_eval(string_data.replace("[", "{").replace("]", "}").replace(":", ": '").replace(", ", "', ") + "'")
print("Converted dictionary:", result)
except (ValueError, SyntaxError) as e:
print("Error in conversion:", e)
# Fallback to split method
result = {sub.split(":")[0]: sub.split(":")[1] for sub in string_data[1:-1].split(", ")}
print("Using split method:", result)
Error in conversion: malformed node or string: line 1
Using split method: {'name': 'John', 'age': '25', 'city': 'NYC'}
Comparison
| Method | Security | Data Types | Best For |
|---|---|---|---|
split() |
Safe | Strings only | Simple string key-value pairs |
eval() |
Risky | Preserves types | Trusted input with numeric values |
ast.literal_eval() |
Safe | Preserves types | Literal expressions only |
Conclusion
Use split() method for simple string conversions as it's the safest approach. Avoid eval() with untrusted input due to security risks. For numeric data, consider ast.literal_eval() as a safer alternative to eval().
