Python: Split a String into a Dictionary

One may come across a situation where one would want to split a string into a dictionary in Python. In such case we can make use of the built-in split() function.

Note that the String should be formatted in a way that can be converted into a dictionary.


Example:

country_city_string = "Tuvalu=Funafuti Nauru=Yaren Kiribati=Tarawa Tonga=Nuku'alofa Palau=Ngerulmud"
country_city_pairs = country_city_string.split()

data_dict = {}
for pair in country_city_pairs:
    country, city = pair.split('=')
    data_dict[country] = city

print(data_dict)
Output:
{'Tuvalu': 'Funafuti', 'Nauru': 'Yaren', 'Kiribati': 'Tarawa', 'Tonga': "Nuku'alofa", 'Palau': 'Ngerulmud'}

You may get the below errors if the string is not well formatted to convert to a list.

ValueError: too many values to unpack (expected 2)

ValueError: not enough values to unpack (expected 2, got 1)

Python String to Dict Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!