通过字典中的字典进行一行迭代

Art*_*oev 2 python dictionary python-3.x

G2 = {'a': {'c': 1, 'b': 1}, 'b': {'a': 1, 'c': 1}}

b = G2.values()

for i in b:
    for key, value in i.items():
        list.append(key)

#result: ['c', 'b', 'a', 'c']
Run Code Online (Sandbox Code Playgroud)

我可以得到相同的结果但使用列表生成器吗?我是这样试的:

list2 = [key for key, value in i.items() for i in b]

#but i get: ['a', 'a', 'c', 'c']
Run Code Online (Sandbox Code Playgroud)

Jea*_*bre 6

只需使用 链接字典值(又名键)itertools.chain.from_iterable,然后转换为列表以打印结果:

import itertools

G2 = {'a': {'c': 1, 'b': 1}, 'b': {'a': 1, 'c': 1}}

#['c', 'b', 'a', 'c']

result = list(itertools.chain.from_iterable(G2.values()))

print(result)
Run Code Online (Sandbox Code Playgroud)

结果:

['c', 'b', 'c', 'a']
Run Code Online (Sandbox Code Playgroud)

请注意,在迭代字典键时不能保证顺序。

itertools在理解中不使用展平双循环的变体(这可能更接近您的尝试):

result = [x for values in G2.values() for x in values]
Run Code Online (Sandbox Code Playgroud)