ravi ravi - 15 days ago 6
Python Question

In Python dictionary how to find a based on first value of the key?

I am working with python dictionary to store the key value pair. I have duplicate keys such as for key 6 there are to values [4,2], [5,1], which i can not store in the dictionary since it doesn't allow duplicate keys.

Therefore, I came up with indexing the key itself e.g. for key 7 there are 3 values so I stored them with index as

{(7, 0): [6, 1], (7, 1): [5, 2], (7, 2): [4, 3]}

Based on above logic I generated the following dictionary.

{
(7, 0): [6, 1],
(7, 1): [5, 2],
(7, 2): [4, 3],

(6, 1): [4, 2],
(6, 0): [5, 1],

(5, 0): [4, 1],
(5, 1): [3, 2],

(3, 0): [2, 1],

(4, 0): [3, 1]
}


My question is that how to find a set of values for a given key e.g. for key 7 I want to get the result as [6,1], [5,2], [4,3].

PS: Only python2.7 standard libraries should be used for the solution.

Thanks for your help.

Answer

For your answer:

print([v for k,v in d.items() if k[0]==7])

result:

[[6, 1], [5, 2], [4, 3]]

but you're not taking advantage of the dictionary. For your task I would suggest collections.defaultdict with list as default argument

Demo:

import collections

d = collections.defaultdict(list)

d[7].append([6,1])
d[7].append([5,2])
d[7].append([4,3])

print(d[7])

result:

[[6, 1], [5, 2], [4, 3]]
Comments