如何从复杂的字典D中提取嵌套数据,并从它们中构建新的字典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']}

最佳答案

您可以执行以下操作

如您所知,可以用其keys,其valueskeysvalues称为items的字典来调用字典(所有信息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']}


pythonic少了一点,但是可以用。

关于python-3.x - 如何从复杂的词典中提取嵌套数据并从中构建新的词典?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46077919/

10-08 21:00