1

I am having trouble getting past a limitation of the 'index' function when it is confronted with repeating values.

Specifically, for given values within a dictionary in which are there repeats (like the example below), is there a way to retrieve the index of every occurrence of a value, not just the first one?

example_dict={'ABAB': [9,10,6,6,6]}
example_dict['ABAB'].index(6) # returns 2

My goal is to use these indices later on in my work. So I need to know that 9 is index 0, 10 is index 1, and that 6 is index 2, 3, and 4 in the values (not just 2).

Could someone please provide a tip for a workaround for this? Thank you very much for your help.

Z_D
  • 797
  • 2
  • 12
  • 30

3 Answers3

2

This should do the trick:

>>> example_dict = {'ABAB': [9,10,6,6,6]}                                                                                                             
>>> [i for i, x in enumerate(example_dict['ABAB']) if x == 6]
[2, 3, 4]     
adder
  • 3,512
  • 1
  • 16
  • 28
2

Try a list comprehension:

[i for i, x in enumerate(example_dict['ABAB']) if x == 6]

For more discussion.

cody
  • 86
  • 1
  • 5
0
zz = {'a', [1,2,3,6,6,6,3,5,7,7,9,2]}
y = { }
K = [ ]
for z in zz :
    for i in zz[z] :
        y.setdefault(i , [zz[z].index(i)])
        ii = zz[z].index(i)
        zz[z][ii] = None
        if i not in k :
            k.append(i)
        if i in zz[z] and i in k :
            y[i].append(zz[z].index(i))
print(y)