Home > Software engineering >  convert nested tuples in lists into a dictionary and add new key values
convert nested tuples in lists into a dictionary and add new key values

Time:07-29

i am trying to convert these nested tuples into a dictionary

country_list = [[('Finland', 'Helsinki')], [('Sweden', 'Stockholm')], [('Norway', 'Oslo')]]

and to add custom key values to such as the output would be

[{'country': 'FINLAND', 'city': 'HELSINKI'},
{'country': 'SWEDEN', 'city': 'STOCKHOLM'},
{'country': 'NORWAY', 'city': 'OSLO'}]

i've done this:

new_country=[list(country) for sublist in 
country_list for country in sublist]
print(new_country)

which obviously returns a list, i have tried using the dict() function but it throws an error, and i am not sure how to add these custom key values

CodePudding user response:

Try:

[{'country':i[0][0],'city':i[0][1]} for i in country_list]

output:

[{'country': 'Finland', 'city': 'Helsinki'},
 {'country': 'Sweden', 'city': 'Stockholm'},
 {'country': 'Norway', 'city': 'Oslo'}]

To be clear this returns a list of dictionaries, not a dictionary. This does match the desired output though.

  • Related