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?

Answer

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

Source: https://stackoverflow.com/q/67595576

172 5 5 0