Splitting the String and Converting it to Dictionary
Last Updated :
15 Jul, 2025
In Python, we may need to convert a formatted string into a dictionary. For example, given the string "a:1, b:2, c:3"
, we want to split the string by its delimiters and convert it into a dictionary. Let's explore various methods to accomplish this task.
Using Dictionary Comprehension
We can split the string by commas and colons and construct a dictionary directly using dictionary comprehension.
Python
# Input string
s = "a:1, b:2, c:3"
# Converting string to dictionary
d = {i.split(":")[0]: int(i.split(":")[1]) for i in s.split(", ")}
# Output dictionary
print(d)
Output{'a': 1, 'b': 2, 'c': 3}
Explanation:
- The string is first split by
,
to get key-value pairs. - Each pair is further split by
:
to extract keys and values. - A dictionary is constructed directly using dictionary comprehension.
Let's explore some more ways and see how we can split the string and convert it to dictionary.
Using map with Dictionary Comprehension
This method uses the map() function to process each key-value pair, making the code slightly more modular.
Python
# Input string
s = "a:1, b:2, c:3"
# Converting string to dictionary
d = {k: int(v) for k, v in map(lambda x: x.split(":"), s.split(", "))}
# Output dictionary
print(d)
Output{'a': 1, 'b': 2, 'c': 3}
Explanation:
- map() function is used to split each key-value pair into a tuple of key and value.
- A dictionary comprehension constructs the dictionary from the tuples.
- This method is modular and avoids repetitive splitting.
Using For Loop
We can use a simple for loop to manually split and construct the dictionary.
Python
# Input string
s = "a:1, b:2, c:3"
# Converting string to dictionary
pairs = s.split(", ")
d = {}
for pair in pairs:
key, value = pair.split(":")
d[key] = int(value)
# Output dictionary
print(d)
Output{'a': 1, 'b': 2, 'c': 3}
Explanation:
- The string is first split into key-value pairs using
,
. - Each pair is split by
:
and added to the dictionary in the loop. - This method is straightforward and easy to understand but less concise than other methods.
Using eval()
This method works if the input string is formatted like a Python dictionary. It is less safe but useful in specific cases.
Python
# Input string
s = "{'a': 1, 'b': 2, 'c': 3}"
# Converting string to dictionary
d = eval(s)
# Output dictionary
print(d)
Output{'a': 1, 'b': 2, 'c': 3}
Explanation:
- eval() function directly interprets the string as Python code.
- This method only works for strings formatted as Python dictionary literals.
- It is not recommended for untrusted input due to security risks.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice