Extract all keys in the second level of nested dictionary

独自空忆成欢 提交于 2021-02-09 06:58:47

问题


I would like to extract all keys in second level of 2d dictionary but python interpreter return NameError. my expected result is ['aa', 'bb', 'cc', 'aaa', 'bbb', 'ccc']

>>> adict
defaultdict(<class 'dict'>, {'b': {'aaa': 444, 'ccc': 666, 'bbb': 555}, 'a': {'aa': 111, 'cc': 333, 'bb': 222}})

>>> all = [ele for ele in adict[ww].keys() for ww in ['a', 'b']]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'ww' is not defined

回答1:


You're close. You just need to re-order your loops:

all = [ele for ww in ['a', 'b'] for ele in adict[ww] ]

To understand why, think about how you'd write a normal for loop:

all = []
for ww in ['a', 'b']:
    for ele in adict[ww]:
        all.append(ele)

Notice the order of the loops remains the same. Also, I've dropped the .keys(), it isn't necessary because iteration on a dict by default happens over the keys.


You can also be awesome like Jon Clements and do this:

In [265]: set().union(*adict.values())
Out[265]: {'aa', 'aaa', 'bb', 'bbb', 'cc', 'ccc'}

*adict.values() returns a list of inner dictionaries, whose keys are unpacked and then added to a set. Some pointers:

  1. Order not guaranteed (even on python3.6)

  2. Duplicates are dropped




回答2:


adict = {'b': {'aaa': 444, 'ccc': 666, 'bbb': 555}, 'a': {'aa': 111, 'cc': 333, 'bb': 222}}

[key for nested_dict_key, nested_dict_value in adict.iteritems() for key, value in nested_dict_value.iteritems()]


来源:https://stackoverflow.com/questions/45652155/extract-all-keys-in-the-second-level-of-nested-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!