0

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.

KayB
  • 3
  • 2
  • your algorithm runs in O(n**2) time; `.index()` performs linear search from the beginning each time it is called. Also it is unclear how you ask for the *index* of the values in the list, but in your expected output, you ask for the values themselves… – taylor swift Mar 23 '17 at 00:58
  • Possible duplicate of [Finding the index of an item given a list containing it in Python](http://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python) – KayB Mar 23 '17 at 01:11

2 Answers2

1

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.

Miriam Farber
  • 18,986
  • 14
  • 61
  • 76
0

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']})
James
  • 32,991
  • 4
  • 47
  • 70