How to add an index to a dict

For example, given:

['A', 'B', 'A', 'B']    

I want to have:

{'A': [0, 2], 'B': [1, 3]}

I tried a loop that looks like; add the index where the character is found, then replace it with '', so the next time you go through the loop, it goes to the next character.

However, these loops do not work for other reasons, and I got stuck not knowing how to proceed.

+4
source share
4 answers

A simple understanding of the dictionary should do the trick:

{key: [index for index, x in enumerate(my_list) if x == key] for key in my_list}

Simple procedure:

>>>> my_list = ['A','B','A','B']
>>>> {key: [index for index, x in enumerate(my_list) if x == key] for key in my_list}
>>>> {'A': [0, 2], 'B': [1, 3]}

How it works

The list of concepts is often used in Python as syntactic sugar for the for loop. Instead of writing

my_list = []
for item in range(10):
    my_list.append(item)

:

my_list = [item for item in range(10)]

, , , . - , , - .

. , , , .

:

{k: None for k in ["Hello", "Adele"]}
>>>> {"Hello": None, "Adele": None}

, , ,

  • key my_list
  • key my_list

, :

my_dict = {}
for key in my_list:
    indices = []
    for index,value in enumerate(my_list):
         if value == key:
              indices.append(index)
    my_dict[key] = indices

enumerate , . , .

:

 enumerate(['a','b','a','b'])
 >>>> [(0,'a'),(1,'b'),(2,'b'),(3,'b')]

enumerate.

, - . , : . - , . .

. @wilinx . @Rob set(my_list), .

+3

enumerate setdefault:

example = ['a', 'b', 'a', 'b']
mydict = {}
for idx, item in enumerate(example):
     indexes = mydict.setdefault(item, [])
     indexes.append(idx)
+9

defaultdict itertools:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> 
>>> for i,x in enumerate(l):
        d[x].append(i)


>>> d
defaultdict(<class 'list'>, {'A': [0, 2], 'B': [1, 3]})
+3

All you need is to use the correct DataType for you . Check out this link - python doc. Good luck. Hope this helps.

Source: https://docs.python.org/2/library/collections.html#collections.OrderedDict

>>> # regular unsorted dictionary
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

>>> # dictionary sorted by key
>>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
-1
source

All Articles