Reputation: 4636
I have this two lists, with same 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:
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?
Upvotes: 4
Views: 547
Reputation: 11183
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 = {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]}
Upvotes: 0
Reputation: 35626
Something like defaultdict + zip could work here:
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]}
Upvotes: 6