-4

以下两个列表匹配,所以 Alice 的年龄是 20 岁,Bob 的年龄是 21 岁,依此类推。

names = ["Alice", "Bob", "Cathy", "Dan", "Ed", "Frank", "Gary", "Helen", "Irene", "Jack", "Kelly", "Larry"]
ages = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]

编写一个程序,将这些列表组合成一个字典。键是年龄,值是名称,因此键可以有多个值,如下所示:

{20: ['Alice', 'Frank', 'Gary'], 
 21: ['Bob'], 
 18: ['Cathy', 'Dan'], 
 19: ['Ed', 'Helen', 'Irene', 'Jack', 'Larry'], 
 22: ['Kelly']}

我已经尝试了一些这样的事情:

newDict = dict(zip(ages, names)) print(newDict)

他们都输出:{20:'Gary',21:'Bob',18:'Dan',19:'Larry',22:'Kelly'}

4

1 回答 1

0

尝试这个:

from collections import defaultdict
age_name = defaultdict(list)

for age, name in zip(ages, names):
    age_name[age].append(name)

Defaultdicts 非常有用。它们会自动为新密钥创建默认容器。

编辑:不使用默认字典

age_name = dict()
for age, name in zip(ages, names):
    if age not in age_name.keys():
        age_name[age] = list()
    age_name[age].append(name)
于 2019-11-11T17:08:59.823 回答