ravi
ravi

Reputation: 1088

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.

Upvotes: 1

Views: 600

Answers (4)

Monica
Monica

Reputation: 27

So I tried doing something like this. Might this solve your problem?

for key in dict:
    for val in key:
        if val == 7:
            print 'yes'

Upvotes: 0

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48067

Your approach for creating a dict is not Good. Instead of doing this, you should create a dict which holds values of all your items as list.

Hence, your dictionary structure should be like:

my_dict = {
    7: [[6, 1], [5, 2], [4, 3]],
...
}

Then you can simply access all the values of 7 with:

my_dict[7]

Take a look at collections.defaultdict.


If you still want to go with your approach, you may use list comprehension to fetch the values as:

key = 7

[v for k , v in my_dict.items() if k[0]==key]
#                                   ^  matches 0th index of key and returns
#                                      returns all the values as list     

Upvotes: 2

Jean-François Fabre
Jean-François Fabre

Reputation: 140168

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]]

Upvotes: 2

gr1zzly be4r
gr1zzly be4r

Reputation: 2152

I would actually change the structure of your dictionary a bit to make it a dictionary that had numbers for keys (i.e., your 6 and 7 that you're talking about here) and then list of tuples for the values. Like this:

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

You could also have a list of lists if you wanted.

Upvotes: 1

Related Questions