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)
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]})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With