Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert nested tuples in lists into a dictionary and add new key values

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading