将两个列表合并到一个以唯一值作为键的字典中

我有这两个列表,具有相同的 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

有没有更pythonic的方法来做到这一点?

回答

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


以上是将两个列表合并到一个以唯一值作为键的字典中的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>