Questions

How to insert multiple values for a key in python dictionary?

0

I have an input like this:

13
1 2 3 1 4 5 6 4 2 2 3 2 7

where first line tells the number of values that is to be taken and second line represents all those values space seperated.

I want to store all the positions of each number in a dictionary like below:

{
  1: [0, 3], 
  2: [1, 8, 9, 11], 
  3: [2, 10], 
  4: [4, 7], 
  5: [5], 
  6: [6], 
  7: [12]
}

How we can do that?



asked 1 year, 11 months ago
Reputation: 1





1 Answer

0

We can do this using setdefault functionality of python

n,q = map(int, input().split())

data={}

values = list(map(int, input().split()))


for i in range(n):
    data.setdefault(values[i],[]).append(i)


print (data)

answered 1 year, 11 months ago
Reputation: 1





Your Answer

Nothing to preview

Post Answer



Asked:  1 year, 11 months ago
Viewed:  394 times
Active:  1 year, 11 months ago