在字典 python 中按顺序获取每个键中的每个值

问题描述 投票:0回答:2

我在从字典中获取值时遇到问题。 例如,我有字典: dct={'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]} 我想按顺序获取每个键中的每个值。 输出应该是这样的:

1
4
7
2
5
8
3
6
9

说明: 1-键'a'中的第一个值,4-键'b'中的第一个值,7-键'c'中的第一个值,键'a'中的 2-秒值,键'b'中的 5-秒值等)

提前谢谢你!

我试过这个版本:

dct={'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]}

for key, val in dct.items():
  for i in range(len(val)):
    print(val[i])

但是没用

python dictionary items
2个回答
2
投票

您当前的代码按照每个值在每个列表中出现的顺序打印每个值,而不是按所需顺序打印值(即,每个键的第一个值按顺序排列,然后每个键的第二个值按顺序排列,依此类推) .

实现所需输出的一种方法是使用嵌套循环按顺序迭代每个键中的值:

dct = {'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}

# Get the length of the longest list
max_len = max(len(lst) for lst in dct.values())

# Loop over each index in the range of the longest list
for i in range(max_len):
    # Loop over each key in alphabetical order
    for key in sorted(dct.keys()):
        # If the key has a value at the current index, print it
        if i < len(dct[key]):
            print(dct[key][i])

0
投票

这应该可以解决问题:

from itertools import chain

result = list(chain(*zip(*dct.values())))

解释:我们从 dict 中收集值,将它们压缩,生成类似

[(1, 4, 7), (2, 5, 8)...]
的东西,然后用
chain

展平这个列表
© www.soinside.com 2019 - 2024. All rights reserved.