1:n values in dictionary python -


i have trouble achieve simple task.

i have 2 lists (same length) 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 build dictionary keys taken f1 , values should lists of numbers (f2 contains unique ids) of 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 zip surely missed , last items appended:

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

thanks suggestion

the problem d[i] = [] overwrite entry 'shallow' or 'deep' new, empty list. want if it's not present yet:

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

alternatively, use defaultdict handle automatically:

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

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -