addicted
addicted

Reputation: 3051

comparing values in two or more keys in python dict

I want to compare the values for 2 or more keys in python dict and return the highest value. I can find max for 2 keys but I am clueless for 3 keys and above.

Here is my code for 2 keys comparison:

d = {}
d['right'] = [0.1, 0.3, 0.5]
d['left'] = [0.2, 0.1, 0.4]
result = [list(d)[0] if x > y else list(d)[1] for x,y in zip(list(d.values())[0], list(d.values())[1])]
# result: ['left', 'right', 'right']

now what's the best way to do it for 3 keys?

# input:
d = {}
d['right'] = [0.1, 0.3, 0.5]
d['left'] = [0.2, 0.1, 0.4]
d['back'] = [0.0, 0.2, 0.8]
# expected result: ['left', 'right', 'back']

PS: I try not to use numpy, pandas, or any library possible. Or if I have to use, I try to stick with whatever base library available in python.

Upvotes: 0

Views: 77

Answers (3)

Scott Boston
Scott Boston

Reputation: 153460

You can try something like this:

l1 = zip(*d.values())
l2 = list(d.keys())

[l2[i.index(max(i))] for i in l1]

Output:

['left', 'right', 'back']

Upvotes: 2

gushitong
gushitong

Reputation: 2016

Construct N dict for N values, and compute each one:

d = {}                                                                              
d['right'] = [0.1, 0.3, 0.5]                                                        
d['left'] = [0.2, 0.1, 0.4]                                                         

dct = [dict(zip(d.keys(), [v[i] for v in d.values()])) for i in range(len(d.values()[0]))]
keys = [sorted(d.keys(), key=lambda key:d[key], reverse=True)[0] for d in dct]
# ['left', 'right', 'right']  

Upvotes: 0

DYZ
DYZ

Reputation: 57033

You should sort the dictionary key/value pairs by values in the descending order:

keys,_ = zip(*sorted(d.items(), key=lambda x:x[1], reverse=True))
keys
#('left', 'right', 'back')

You can use itemgetter instead of the lambda, if you prefer:

from operator import itemgetter
keys,_ = zip(*sorted(d.items(), key=itemgetter(1), reverse=True))

Upvotes: 3

Related Questions