我有一本这样的字典:
{
"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"]
如何逐个循环遍历每个键值,直到到达最后一个列表的数组值的末尾?每个密钥的所有列表的长度都相同。
答案 0 :(得分:1)
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']
答案 1 :(得分:0)
假设所有值的长度相同:
di = {
"month": ["January", "February", "March"],
"volume": [1,2,3],
"target": [6,8,5],
}
sample_length = len(list(di.values())[0])
final_list = []
for j in range(sample_length):
list_item = []
for key, val in di.items():
list_item.append('{}: {}'.format(key, val[j]))
final_list.append(', '.join(list_item))
print(final_list)
输出:
['month: January, volume: 1, target: 6', 'month: February, volume: 2, target: 8', 'month: March, volume: 3, target: 5']
答案 2 :(得分:0)
使用此示例:
di = {
"month": ["January", "February", "March"],
"volume": [1,2,3],
"target": [6,8,5],
}
一个想法就是将其转换为列表
li = [ [k + ": " +str(v) for v in v_list] for k,v_list in test_dict.items()]
然后使用zip进行连接
[ ', '.join(l) for l in zip(*li) ]
这是结果:
['month: January, volume: 1, target: 6',
'month: February, volume: 2, target: 8',
'month: March, volume: 3, target: 5']