【问题标题】:How to loop through two lists to create a dictionary如何遍历两个列表来创建字典
【发布时间】:2016-11-09 07:00:24
【问题描述】:

我想创建一个 dictionary,使用 degree 作为 key,并且值必须是所有获得该学位的学生.下面,sam 接 bcom,jack 接 bcom 等。提前致谢

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

【问题讨论】:

  • 这个问题和以下答案帮助我解决了从两个列表创建字典的问题。这个问题还展示了一个很好的例子,说明当有公共字典键时会发生什么。为问题 +1!

标签: python-3.x loops dictionary


【解决方案1】:

可能是这个 sn-p 做你想做的事:

dictionary = {}
for degree, student in zip(degrees, students):
    dictionary.setdefault(degree, []).append(student)

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

【讨论】:

    【解决方案2】:

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

    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']}

    虽然如果同一个学生攻读两个不同的学位就不行了

    【讨论】:

      猜你喜欢
      • 2011-12-09
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      相关资源
      最近更新 更多