gpt4 book ai didi

python - 迭代字典中的列表

转载 作者:行者123 更新时间:2023-12-01 07:59:06 24 4
gpt4 key购买 nike

我有一本看起来像这样的字典:

{
"month": ["January", "February", "March"],
"volume": [1,2,3],
"target": [6,8,5]
}

我想循环每个键和值,以便我可以创建一个如下所示的列表:

["month: January, volume: 1, target: 6", "month: February, volume: 2, target: 8", "month: March, volume: 3, target: 5"]

如何逐个循环每个键值,直到到达最后一个列表的数组值的末尾?所有列表的每个键的长度都相同。

最佳答案

d = {
"month": ["January", "February", "March"],
"volume": [1,2,3],
"target": [6,8,5]
}

keys = tuple(d) # ('month', 'volume', 'target')
values = tuple(zip(*d.values())) # (('January', 1, 6), ('February', 2, 8), ('March', 3, 5))

your_list = [
', '.join(
f'{keys[i]}: {value[i]}'
for i in range(len(keys)) # range(3) in this case
)
for value in values
]

print(your_list)

输出:

['month: January, volume: 1, target: 6',
'month: February, volume: 2, target: 8',
'month: March, volume: 3, target: 5']

关于python - 迭代字典中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55797059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com