首页 > 解决方案 > 将两个列表合并到一个字典中,以唯一值作为键

问题描述

我有这两个列表,具有相同的 len:

owner=["John","John","Mark","Bill","John","Mark"]
restaurant_number=[0,2,3,6,9,10]

我想把它变成一个通知每个所有者的 restaurant_number 的字典:

d={"John":[0,2,9],"Mark":[3,10],"Bill":[6]}

我可以用丑陋的方式做到这一点:

unique=set(owner)
dict={}
for i in unique:
    restaurants=[]
    for k in range(len(owner)):
        if owner[k] == i:restaurants.append(restaurant_number[k])
    dict[i]=restaurants

有没有更蟒蛇的方式来做到这一点?

标签: pythonlistdictionary

解决方案


defaultdict + zip这样的东西可以在这里工作:

from collections import defaultdict

d = defaultdict(list)

owner = ["John", "John", "Mark", "Bill", "John", "Mark"]
restaurant_number = [0, 2, 3, 6, 9, 10]

for o, n in zip(owner, restaurant_number):
    d[o].append(n)

print(dict(d))
{'John': [0, 2, 9], 'Mark': [3, 10], 'Bill': [6]}

推荐阅读