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.

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!