Reputation: 21
I need to create a method that takes in multiple dictionaries and return the one with biggest value. If some dictionaries share the same max value then it should return the one with bigger key int value.
i.e
p1 = {4:5}
p2 = {4:3}
p3 = {8:2}
p4 = {12:5}
def compare(*args):
#return p4
Upvotes: 0
Views: 589
Reputation: 57085
This code uses the fact that if a dictionary has only one item, that item will be the largest in the dictionary and can be extracted by calling max()
. Each item is then reversed to put the value in front of the key, and the largest item is computed with another call to max()
.
def compare(*dicts):
return max([(max(d.items())[::-1],d) for d in dicts])[-1]
This function is about twice as fast as the one proposed by Olivier Melançon. (lambda
s are always slow.)
Upvotes: 1
Reputation: 22324
Use max
with a key
.
def compare(*dicts):
return max(dicts, key = lambda d: max((v, k) for k, v in d.items()))
p1 = {4:5}
p2 = {4:3}
p3 = {8:2}
p4 = {12:5}
print(compare(p1, p2, p3, p4)) # {12: 5}
Upvotes: 3