Obey Existing
Obey Existing

Reputation: 21

Comparing dictionary with integers as both value and key

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

Answers (2)

DYZ
DYZ

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. (lambdas are always slow.)

Upvotes: 1

Olivier Melançon
Olivier Melançon

Reputation: 22324

Use max with a key.

Code

def compare(*dicts):
    return max(dicts, key = lambda d: max((v, k) for k, v in d.items()))

Example

p1 = {4:5}
p2 = {4:3}
p3 = {8:2}
p4 = {12:5}

print(compare(p1, p2, p3, p4)) # {12: 5}

Upvotes: 3

Related Questions