pythondictionary

1:n values in dictionary python


I have some trouble to achieve a simple task.

I have 2 lists (same length) like this:

f1 = ['Shallow', 'Shallow', 'Shallow', 'Shallow', 'Shallow', 'Deep', 'Deep', 'Deep', 'Shallow', 'Shallow', 'Shallow', 'Shallow', 'Shallow', 'Shallow', 'Shallow', 'Deep', 'Deep']
f2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

what I would like to build is a dictionary with keys taken from f1 and the values should be the lists of numbers (f2 contains some unique ids) of the corresponding key.

Something like:

d = {}
d['Shallow'] = [0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 13, 14]
d['Deep'] = [5, 6, 7, 15, 16]

I tried looping with zip but I surely missed something and only the last items are appended:

d = {}

for i, j in zip(f1, f2):
    d[i] = []
    d[i].append(j)

Thanks for any suggestion


Solution

  • The problem is that d[i] = [] will always overwrite the entry for 'Shallow' or 'Deep' with a new, empty list. What you want is to only do that if it's not present yet:

    d = {}
    
    for i, j in zip(f1, f2):
        if i not in d:
            d[i] = []
        d[i].append(j)
    

    Alternatively, use defaultdict to handle this automatically:

    from collections import defaultdict
    
    d = defaultdict(list)
    
    for i, j in zip(f1, f2):
        d[i].append(j)