如何遍历两个列表来创建字典

时间:2016-11-09 07:00:24

标签: python-3.x loops dictionary

我想创建词典,使用作为,值必须是所有取得该度数的学生。下面,sam采取bcom,jack采取bcom等等。提前谢谢

students = ['sam','jack','rose','khan','marry','xio']
degrees = ['bcom','bcom','bsc','arts','bsc','arts']

2 个答案:

答案 0 :(得分:2)

可能是这个代码片段做你想做的事情:

dictionary = {}
for degree, student in zip(degrees, students):
    dictionary.setdefault(degree, []).append(student)
  <'>''arts':['khan','xio'],'bcom':['sam','jack'],'bsc':['rose','marry']}

答案 1 :(得分:1)

这是实现此行为的另一种紧凑方式:

s2d = dict(zip(students, degrees))
{k: [s for s, d in s2d.items() if d==k] for k in degrees}
  

{'bcom':['sam','jack'],'bsc':['rose','marry'],'arts':['khan','xio']}

虽然如果你有相同的学生将采取两个不同的学位

,它将无效