5
s =['Hello','World','Hello','World'] l = list() for x,y in enumerate(s): l.append((y,x)) 

The output I got is [('Hello', 0), ('World', 1), ('Hello', 2), ('World', 3)]

But I want

Hello-[0,2] World-[1,3] 
3
  • Do you mean you want a dict containing {'Hello': [0, 2], 'World': [1, 3]}? Commented Dec 13, 2016 at 3:08
  • Basically want to convert this into dictionary where Hello and World are my keys and their corresponding values are 0,2 and 1,3 Commented Dec 13, 2016 at 3:08
  • Yes you are right Commented Dec 13, 2016 at 3:09

4 Answers 4

3

You can use a dictionary:

d = {} for i, v in enumerate(s): if v in d: d[v].append(i) else: d[v] = [i] d # {'Hello': [0, 2], 'World': [1, 3]} 
Sign up to request clarification or add additional context in comments.

2 Comments

Here d[v] =[i] that means that [] is for list right?
Correct. if the word is first met, then create a list containing the corresponding index for the key.
3

It seems like collections.defaultdict is a perfect fit for this case (see also the answer of @mhawke) :

from collections import defaultdict dd = defaultdict(list) for idx, item in enumerate(s): dd[item].append(idx) 

Then convert this to a plain dictionary again:

>>> dict(dd) {'Hello': [0, 2], 'World': [1, 3]} 

I recently created a package containing a function that could be used as alternative iteration_utilities.groupedby:

>>> from iteration_utilities import groupedby >>> from operator import itemgetter >>> s =['Hello','World','Hello','World'] >>> groupedby(enumerate(s), key=itemgetter(1), keep=itemgetter(0)) {'Hello': [0, 2], 'World': [1, 3]} 

Comments

2

Use a collections.defaultdict of lists:

from collections import defaultdict d = defaultdict(list) s = ['Hello','World','Hello','World'] for index, key in enumerate(s): d[key].append(index) >>> print(d) defaultdict(<type 'list'>, {'World': [1, 3], 'Hello': [0, 2]}) >>> print(dict(d)) # convert to a std dictionary {'World': [1, 3], 'Hello': [0, 2]} 

Comments

2

This can also be done using a fairly simple dictionary comprehension:

>>> s =['Hello','World','Hello','World'] >>> d = {k: [pos for pos, el in enumerate(s) if el == k] for k in set(s)} >>> d {'World': [1, 3], 'Hello': [0, 2]} >>> 

This works by making keys using each unique element in the list s(which set(s) does), and getting the index of each of the unique elements(which the list comprehension does).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.