Create a dictionary with list items as keys and indexes as values?

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

The result: [('Hello', 0), ('World', 1), ('Hello', 2), ('World', 3)]

But I want

 Hello-[0,2] World-[1,3] 
+5
source share
4 answers

You can use the 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]} 
+3
source

It seems that collections.defaultdict perfect for this case (see also @mhawke's answer):

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

Then convert this to a simple dictionary again:

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

I recently created a package containing a function that can be used as an alternative to 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]} 
+3
source

Use collections.defaultdict 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]} 
+2
source

This can also be done using a fairly simple understanding of the word:

 >>> 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 creating keys using each unique element in the list s (which set(s) does) and getting the index of each of the unique elements (which it understands in the list).

+2
source

Source: https://habr.com/ru/post/1261168/


All Articles