1

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

matteo
  • 4,683
  • 9
  • 41
  • 77

2 Answers2

4

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)
Thomas
  • 174,939
  • 50
  • 355
  • 478
2

There's actually several simple possible ways of finding things in lists. And there are already multiple solutions for this on StackOverflow:

Example 1

Example 2

One simple way would be that python generates list of indexes:

matches = [index for index, value in enumerate(SomeList) if value == 'SomeValue']

So code for your case would be:

f1 = ['Shallow', 'Shallow', 'Shallow', 'Shallow', 'Shallow', 'Deep', 'Deep', 'Deep', 'Shallow', 'Shallow', 'Shallow', 'Shallow', 'Shallow', 'Shallow', 'Shallow', 'Deep', 'Deep']

d = {}
d['Shallow'] = [index for index, value in enumerate(f1) if value == 'Shallow']
d['Deep']    = [index for index, value in enumerate(f1) if value == 'Deep'   ]

print(d)

This would produce next result:

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

This code is not optimized and it "repeats" itselve. Also does not use "f2" list (you can get values from "f2" based on indexes from "f1"). But it's enaugh for understanding general idea.

XOIOX
  • 164
  • 7