Yaroslav
Yaroslav

Reputation: 97

How to extract nested data from a complex dictionary and from them to build a new dictionary?

How to extract nested data from a complex dictionary D and from them to build a new dictionary NS_D?

IN: D= {'10': [{'tea': ['indian', 'green']}], '13': [{'dancing': ['tango', 'step']}], '12': [{'walk': ['running', 'walking']}]}

OUT: NS_D = {'tea': ['indian', 'green'], 'dancing': ['tango', 'step'], 'walk': ['running', 'walking']}

Upvotes: 3

Views: 187

Answers (3)

Andy K
Andy K

Reputation: 5054

You can do the following

As you know, dictionaries can be called with their keys, their values or the keys and the valuescalled items (all the infos here)

In [78]: NS_D = {} 

In [79]: for keys in D.values(): #first loop: parsing through the values
    ...:     for key in keys:    #second loop: parsing through the keys
    ...:         for za,az in key.items(): #third loop: printing keys and values
    ...:             NS_D[za] = az  #you append the keys and values in the dictionary

In [80]: print(NS_D) 
{'tea': ['indian', 'green'], 'dancing': ['tango', 'step'], 'walk': ['running', 'walking']} 

A bit less pythonic but it works.

Upvotes: 3

Djaouad
Djaouad

Reputation: 22776

You can use this :

D= {'10': [{'tea': ['indian', 'green']}], '13': [{'dancing': ['tango', 'step']}], '12': [{'walk': ['running', 'walking']}]}

NS_D = {}
for key, value in D.items():
  NS_D[next(iter(value[0].keys()))] = next(iter(value[0].values()))

print(NS_D)

Which outputs :

{'tea': ['indian', 'green'], 'dancing': ['tango', 'step'], 'walk': ['running', 'walking']}

Upvotes: 2

zipa
zipa

Reputation: 27879

You can do that with combination of list and dict comprehension:

D = {'10': [{'tea': ['indian', 'green']}], '13': [{'dancing': ['tango', 'step']}], '12': [{'walk': ['running', 'walking']}]}
NS_D = {k: v for value in [j[0] for j in D.values()] for k, v in value.items()}
#{'tea': ['indian', 'green'], 'walk': ['running', 'walking'], 'dancing': ['tango', 'step']}

Upvotes: 2

Related Questions