![]() |
VOOZH | about |
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.
We can split the string by commas and colons and construct a dictionary directly using dictionary comprehension.
{'a': 1, 'b': 2, 'c': 3}
Explanation:
, to get key-value pairs.: to extract keys and values.Let's explore some more ways and see how we can split the string and convert it to dictionary.
This method uses the map() function to process each key-value pair, making the code slightly more modular.
{'a': 1, 'b': 2, 'c': 3}
Explanation:
We can use a simple for loop to manually split and construct the dictionary.
{'a': 1, 'b': 2, 'c': 3}
Explanation:
, .: and added to the dictionary in the loop.This method works if the input string is formatted like a Python dictionary. It is less safe but useful in specific cases.
{'a': 1, 'b': 2, 'c': 3}
Explanation: