嵌套字典的键集

set of keys for nested dictionaries

我有几行来填充 set

x = {1: {2: 4, 3: 6}, 5: {2:6, 10: 25, 14: 12}}

keys = set()
for y in x:
    for z in x[y]:
        keys.add(z)

# keys is now `set([2, 3, 10, 14])`

我无法摆脱我可以做得更好的感觉,但我想出的任何东西似乎都不是很好。大多数实现首先构建一个 list,这很烦人。 y中有很多x,大多数y有相同的z

# Builds a huuuuge list for large dicts.
# Adapted from 
keys = set(itertools.chain(*x.values()))

# Still builds that big list, and hard to read as well.
# I wrote this one on my own, but it's pretty terrible.
keys = set(sum([x[y].keys() for y in x], []))

# Is this what I want?
# Finally got the terms in order from 
keys = {z for y in x for z in x[y]}

原始代码是 "most pythonic" 还是其中一种更好?还有别的吗?

您可以使用 dict.items():

x = {1: {2: 4, 3: 6}, 5: {2:6, 10: 25, 14: 12}}
final_x = set(i for b in [b.keys() for i, b in x.items()] for i in b)

输出:

set([2, 3, 10, 14])

我会使用 itertools 模块,特别是 chain class.

>>> x = {1: {2: 4, 3: 6}, 5: {2:6, 10: 25, 14: 12}}
>>> from itertools import chain
>>> set(chain.from_iterable(x.itervalues()))
set([2, 3, 10, 14])

我会用

{k for d in x.itervalues() for k in d}

itervalues()(只是 values() in Python 3)不构建列表,并且此解决方案不涉及字典查找(与 {z for y in x for z in x[y]} 相反).