簡體   English   中英

如何將 2 個列表組合成一個字典,其中鍵可以有多個值?

[英]How to combine 2 lists into a dictionary, where keys can have multiple values?

以下兩個列表匹配,所以 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)

他們都是 output:{20:'Gary',21:'Bob',18:'Dan',19:'Larry',22:'Kelly'}

嘗試這個:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM