Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 字典中字典的单行迭代_Python_Python 3.x_Dictionary - Fatal编程技术网

Python 字典中字典的单行迭代

Python 字典中字典的单行迭代,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,使用列表生成器可以得到相同的结果吗? 我这样试过: 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'] 只需使用itertools.chain.from\u iterable链接字典值(也称为键),然后转换为

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

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']

只需使用
itertools.chain.from\u iterable
链接字典值(也称为键),然后转换为列表以打印结果:

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

#but i get: ['a', 'a', 'c', 'c']
结果:

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)
请注意,在迭代字典键时,不能保证顺序

不使用
itertools
的变体,具有平坦的双循环内部理解(这可能更接近您的尝试):

['c', 'b', 'c', 'a']
result = [x for values in G2.values() for x in values]