Accessing flat list from nested dictionary

Question:

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

['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 🙂

Asked By: BotRex

||

Answers:

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']
Answered By: God Is One
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.