[英]Combine two lists in one dictionary that takes unique values as keys
I have this two lists, with same len:我有这两个列表,具有相同的 len:
owner=["John","John","Mark","Bill","John","Mark"]
restaurant_number=[0,2,3,6,9,10]
I want to turn that into a dict that informs the restaurant_number of each owner:我想把它变成一个通知每个所有者的 restaurant_number 的字典:
d={"John":[0,2,9],"Mark":[3,10],"Bill":[6]}
I could do it the ugly way:我可以用丑陋的方式做到这一点:
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
Is there a more pythonic way to do that?有没有更蟒蛇的方式来做到这一点?
Something like defaultdict + zip could work here:像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]}
Without dependencies.没有依赖。
Given your input:鉴于您的输入:
owner=["John","John","Mark","Bill","John","Mark"]
restaurant_number=[0,2,3,6,9,10]
Prepare the recipient dictionary res
having empty list as values, then populate it without the need to zip:准备具有空列表作为值的收件人字典
res
,然后在不需要 zip 的情况下填充它:
res = {own: [] for own in set(owner)}
for i, own in enumerate(owner):
res[own].append(restaurant_number[i])
To get the result得到结果
print(res)
#=> {'Mark': [3, 10], 'Bill': [6], 'John': [0, 2, 9]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.