KayB
KayB

Reputation: 3

Python: How do I consistently find the next index after another index in a list with duplicates?

Sorry if the question wasn't clear enough, I am very new to python. I also apologize in advance if there are any typos in my code.

Say I have a list

list = [a,b,c,a,x,y,b,m,a,z]

And I want to get the index value of the element after each 'a' using a for loop and store it in a dict. (This assumes dict = {} already exists)

for store in list:
    if dict.has_key(store) == False:
        if list.index(store) != len(list)-1:
            dict[store] = []
            dict[store].append(list[list.index(store)+1])
    else:
        if list.index(store) != len(list)-1:
            dict[store].append(list[list.index(store)+1])

Now ideally, I would want my dict to be

dict = {'a':['b','x','z'], 'b':['c','m'], 'c':['a']....etc.}

Instead, I get

dict = {'a':['b','b','b'], 'b':['c','c'], 'c':['a']...etc.}

I realized this is because index only finds the first occurrence of variable store. How would I structure my code so that for every value of store I can find the next index of that specific value instead of only the first one?

Also, I want to know how to do this only using a for loop; no recursions or while, etc (if statements are fine obviously).

I apologize again if my question isn't clear or if my code is messy.

Upvotes: 0

Views: 47

Answers (2)

Miriam Farber
Miriam Farber

Reputation: 19634

You can do it like that:

l = ['a','b','c','a','x','y','b','m','a','z']
d={}
for i in range(len(l)-1):
    if not l[i] in d:
        d[l[i]] = []
    d[l[i]].append(l[i+1])

Then d is

{'a': ['b', 'x', 'z'],
 'b': ['c', 'm'],
 'c': ['a'],
 'm': ['a'],
 'x': ['y'],
 'y': ['b']}

Regarding your code, there is no need to use index, as you already enumerating over the list, so you do not need to search for the place of the current element. Also, you can just enumerate until len(l)-1, which simplifies the code. The problem in your code was that list.index(store) always finds the first appearance of store in list.

Upvotes: 0

James
James

Reputation: 36608

This looks like a job for defaultdict. Also, you should avoid using list and dict as variables since they are reserved words.

from collections import defaultdict

# create a dictionary that has default value of an empty list
# for any new key
d = defaultdict(list)

# create the list
my_list = 'a,b,c,a,x,y,b,m,a,z'.split(',')

# create tuples of each item with its following item
for k,v in zip(my_list, my_list[1:]):
    d[k].append(v)

d 
# returns:
defaultdict(list,
            {'a': ['b', 'x', 'z'],
             'b': ['c', 'm'],
             'c': ['a'],
             'm': ['a'],
             'x': ['y'],
             'y': ['b']})

Upvotes: 0

Related Questions