Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make dict element value as list in Python

I have a list. Let's say [3,4,2,3,4,2,1,4,5].

I need to create a dictionary from the indexes of the elements.

Here in this case, I need to create a dict as follows:

{
   '3':[0,3],
   '4':[1,4,7],
   '2':[2,5],
   '1':[6],
   '5':[8]
}

where the element values are the indexes of the keys in list provided.

I've tried. But was able to change the values as integers only. But unable to make them as list.

Is there any way to do this with just 1 for loop?

The code I've tried:

d=dict()
ll=[1,2,1,2,1,2,3,4,5,5,4,2,4,6,5,6,78,3,2,4,5,7,8,9,4,4,2,2,34,5,6,3]
for i,j in enumerate(ll):
    d[j].append(i)
print(d)
like image 948
Sukumar Avatar asked Jan 27 '23 13:01

Sukumar


1 Answers

You can use collections.defaultdict with enumerate for an O(n) solution:

from collections import defaultdict

d = defaultdict(list)

A = [3,4,2,3,4,2,1,4,5]

for idx, val in enumerate(A):
    d[val].append(idx)

print(d)

defaultdict(list, {1: [6], 2: [2, 5], 3: [0, 3], 4: [1, 4, 7], 5: [8]})
like image 100
jpp Avatar answered Jan 30 '23 04:01

jpp