如何在字典的列表列表上迭代键?

时间:2019-09-02 02:10:15

标签: python dictionary nested

我现在对此有些困惑。我想获取一个键列表,然后在一个列表列表上进行迭代

tests = ['test 1', 'test 2', 'test 3']
scores = [[90, 70, 60], [40, 50, 100], [60, 65, 90], [30, 61, 67], 
[80, 79, 83], [70, 97, 100]]

预期结果:

我想返回一个显示以下内容的字典:

'test 1': 90,'test 2' : 70, 'test 3': 60, 'test 1': 40, 'test 2': 50, 
'test 3': 100... 'test 1' : 70, 'test 2' : 97, 'test 3':100

测试1:得分1

测试2:得分2

测试3:得分3

2 个答案:

答案 0 :(得分:4)

dictzip一起使用:

[dict(zip(tests, score)) for score in scores]

输出:

[{'test 1': 90, 'test 2': 70, 'test 3': 60},
 {'test 1': 40, 'test 2': 50, 'test 3': 100},
 {'test 1': 60, 'test 2': 65, 'test 3': 90},
 {'test 1': 30, 'test 2': 61, 'test 3': 67},
 {'test 1': 80, 'test 2': 79, 'test 3': 83},
 {'test 1': 70, 'test 2': 97, 'test 3': 100}]

答案 1 :(得分:2)

字典不能包含重复的键,但是,您可以使用元组列表:

tests = ['test 1', 'test 2', 'test 3']
scores = [[90, 70, 60], [40, 50, 100], [60, 65, 90], [30, 61, 67], [80, 79, 83], [70, 97, 100]]
result = [(a, b) for i in scores for a, b in zip(tests, i)]

输出:

[('test 1', 90), ('test 2', 70), ('test 3', 60), ('test 1', 40), ('test 2', 50), ('test 3', 100), ('test 1', 60), ('test 2', 65), ('test 3', 90), ('test 1', 30), ('test 2', 61), ('test 3', 67), ('test 1', 80), ('test 2', 79), ('test 3', 83), ('test 1', 70), ('test 2', 97), ('test 3', 100)]

更好的方法是按目标键将整数分组:

from collections import defaultdict
d = defaultdict(list)
for i in scores:
   for a, b in zip(tests, i):
      d[a].append(b)

print(dict(d))

输出:

{'test 1': [90, 40, 60, 30, 80, 70], 'test 2': [70, 50, 65, 61, 79, 97], 'test 3': [60, 100, 90, 67, 83, 100]}