Python list and dictionary comprehension

Viewed 65

I am trying to get use to list dictionaries comprehension. Here a small code I have not been able to transform.

lst = ['C', 'A', 'B', 'A']
myd = {}
for v, k in enumerate(lst):
    if k in myd:
        myd[k].append(v)
    else:
        myd[k] = [v]

print(myd)

>>> {'C': [0], 'A': [1, 3], 'B': [2]}

I would be please to have some help.

2 Answers

Here is the answer, although I think the non comprehension approach is much easier to understand. And as mentioned this is not efficient in the least.

I would stay with what you have.

{k:[i for i, j in enumerate(lst) if j == k] for k in set(lst)}

A hack with a helper dict, but at least it's linear time.

>>> {k: d.setdefault(k, []).append(i) or d[k]
     for d in [{}]
     for i, k in enumerate(lst)}
{'C': [0], 'A': [1, 3], 'B': [2]}

A variation:

>>> {k: d.setdefault(k, [i])
     for d in [{}]
     for i, k in enumerate(lst)
     if k not in d or d[k].append(i)}
{'C': [0], 'A': [1, 3], 'B': [2]}
Related