0

Having a list like this

lst = ['a','b','a','c','a','b','b']

I'd like to get lists of indexes for each unique element to get this:

indexes = {
            'a': [0,2,4],
            'b': [1,5,6],
            'c': [3]
          }

This is my current code, but I'm only getting the first index of each element.

indexes= dict()
for el in lst:
    indexes[el] = [lst.index(el)]

>>> indexes
{'a': [0], 'b': [1], 'c': [3]}

Thanks for any help.

Ger Cas
  • 2,188
  • 2
  • 18
  • 45
  • Does this answer your question? [How to find all occurrences of an element in a list?](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – blutab Jul 25 '20 at 07:24

1 Answers1

2

The problem with you code is you're overriding the same key again and again but with a different list, so your final dictionary contains only a single list.

you can avoid this behavior by using defaultdict.

from collections import defaultdict

lst = ["a", "b", "a", "c", "a", "b", "b"]
lst = [c for c in lst if c.strip()]  # this will remove empty strings

indexes = defaultdict(list)

for index, char in enumerate(lst):
    indexes[char].append(index)

indexes = dict(indexes)
print(indexes)

Output:

{'a': [0, 2, 4], 'b': [1, 5, 6], 'c': [3]}
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
  • @GerCas I've updated the answer handling the empty strings. – Vishal Singh Jul 25 '20 at 07:43
  • Thanks Vishal. I think I didn't explain very well. I mean get rid of empty keys in output dictionary without affecting the original indexes. If I remove empty values in input list, the indexes of output dictionary change. – Ger Cas Jul 25 '20 at 07:52
  • you'll never have an empty string because only integers are appended in that list. – Vishal Singh Jul 25 '20 at 07:54
  • Try with your current code this input list `["a", "b", "a", "c", "a", "b", "b"]` and compare output dictionary with this other input list `["a", "b", "", "a", "c", "", "a", "b", "b", ""]` You'll see the indexes are different – Ger Cas Jul 25 '20 at 07:56
  • if I understood your problem correctly I think you're looking for `indexes.pop('')`. – Vishal Singh Jul 25 '20 at 07:59
  • Exactly. Is easiest that I expected. That happens when someone is a beginner hehe. Thanks so much – Ger Cas Jul 25 '20 at 08:03