提取嵌套字典第二级中的所有键 [英] Extract all keys in the second level of nested dictionary

查看:71
本文介绍了提取嵌套字典第二级中的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提取2d字典第二级中的所有键,但是python解释器返回NameError.我的预期结果是['aa','bb','cc','aaa','bbb','ccc']

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

推荐答案

您已经关闭.您只需要对循环进行重新排序:

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

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

要了解原因,请考虑如何编写普通的 for 循环:

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)

请注意,循环顺序保持不变.另外,我还删除了 .keys(),这是没有必要的,因为默认情况下,在 dict 上的迭代发生在键上.

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.

您也可以像乔恩·克莱门茨(Jon Clements)一样出色,并执行以下操作:

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

* adict.values()返回内部字典的列表,将其键解包然后添加到集合中.一些指针:

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

  1. 不能保证顺序(即使在python3.6上也是如此)

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

重复项被删除

这篇关于提取嵌套字典第二级中的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆