Home > Blockchain >  Iterate through nested dictionary for keys of new dictionary
Iterate through nested dictionary for keys of new dictionary

Time:05-04

I have a nested dictionary and I need to iterate through one of the keys from inner dictionary to make it the key for a new (separate) dictionary. How. this is the structure of the nested dictionary:

 'Malawi': {'continent': 'Africa', 'gdpPerCapita': 1005, 'population': 18898441, 'area': 118484}, 'Somalia': {'continent': 'Africa', 'gdpPerCapita': 941, 'population': 16360000, 'area': 637657}

and I need to make a dictionary with the key being each continent.

CodePudding user response:

Assuming that your existing dictionary is named d, you can use a dictionary comprehension to create a new dictionary keyed by continent name:

{ v['continent']: v for k, v in d.items() }

However, this loses the country name by which it was originally keyed, and moreover, will cause one of the items in your original dictionary to be lost, since they both have the same continent (Africa).

CodePudding user response:

IIUC this should do the job,

{f"continent_{item[0]}":item[1]["continent"] for item in dict1.items()}
  • Related