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

Accessing flat list from nested dictionary

I have a nested dictionary which contains list as key-value pairs

data ={'Country': {"['USA', 'Russia']":"['A country in North America','A country in Asia']"},'River': {"['Nile', 'Amazon']":"['A river in Africa','A river in South America']"}}
countrylist=[]
temp=[]
country_desc_list=[]
for k in data:
  countrylist.extend(data[k].keys())
  country_desc_list.extend(data[k].values())
  print(countrylist)
  print(country_desc_list)
  countrylist.clear()
  country_desc_list.clear()

but the output is like

["['USA', 'Russia']"]
["['A country in North America','A country in Asia']"]
["['Nile', 'Amazon']"]
["['A river in Africa','A river in South America']"]

I want it to be in the form of a flatlist like

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

['Usa','Russia']
['A country in North America','A country in Asia']

I m new to python so even after few searches I couldn’t figure it out …pls help 🙂

>Solution :

You can get the desired output by:

for x,y in data.items():
    for p,q in y.items():
        print(p,q)

#output
['USA', 'Russia'] ['A country in North America','A country in Asia']
['Nile', 'Amazon'] ['A river in Africa','A river in South America']

if you print like this:

for x,y in data.items():
    for p,q in y.items():
        print(p)
        print(q)

#output
['USA', 'Russia']
['A country in North America','A country in Asia']
['Nile', 'Amazon']
['A river in Africa','A river in South America']
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