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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap