JON PANTAU
JON PANTAU

Reputation: 395

Return the largest key of two dictionary

Assume we have two dictionary:

a = {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7}
b = {0:0, 1:7, 2:6, 3:5, 4:4, 5:3, 6:2, 7:1}

since the keys that have matches key & value pair at 0 and 4 position in dictionary like a[0] == b[0] and a[4] == b[4] but I want to return only key 4 because its higher.

Upvotes: 2

Views: 656

Answers (4)

RoadRunner
RoadRunner

Reputation: 26325

You could also use set intersection here:

a = {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7}
b = {0:0, 1:7, 2:6, 3:5, 4:4, 5:3, 6:2, 7:1}

matches = set(a.items()).intersection(b.items())
# {(0, 0), (4, 4)}

try:
    print(max(matches)[0])
except ValueError:
    print("Cannot get max of empty set")

# 4

Upvotes: 2

Adirio
Adirio

Reputation: 5286

In python 3:

a = {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7}
b = {0:0, 1:7, 2:6, 3:5, 4:4, 5:3, 6:2, 7:1}

max(k for k in a.keys() if k in b and a[k] == b[k])

Take into account that a ValueError will be raised if there is no common pair of keys and values in the 2 dicts. Use a try: ... except ValueError: ... statemente to handle this apropriately.

Lets break it into part to understand it more precisely:

[k for k in a.keys()]

List-comprehension that will iterate over all the keys in the first dict (a). Now we want to filter it:

[k for k in a.keys() if k in b]

This first filtering step ensures that the key is also in the second dict (b).

[k for k in a.keys() if k in b and a[k] == b[k]]

And this second step ensures that the values of both dicts are the same for this key. So by now we have a list with all the keys that have the same value in both dicts.

max([k for k in a.keys() if k in b and a[k] == b[k]])

The list-comprehension can be replaced by a generator as we do not need the list itself for anything, so the square brackets can be removed.

max(k for k in a.keys() if k in b and a[k] == b[k])

Compute the maximum of the list. This is where the ValueErrorcan get raised if the list is empty as max([]) raises ValueError. This would mean that there is no common pair of key-values.

try:
    print(max(k for k in a.keys() if k in b and a[k] == b[k]))
except ValueError:
    print("No common pair of key-value.")

Upvotes: 3

Laurent H.
Laurent H.

Reputation: 6526

I suggest you this very basic solution in Python3. Additonnally to the other currently proposed solutions, it does not fail into error if there is no common key/value pairs between the two dictionaries. I also added lots of comments for better understanding and readability:

a = {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7}
b = {0:0, 1:7, 2:6, 3:5, 4:4, 5:3, 6:2, 7:1}

# Initialize the result (output)
result = None

# Get the common keys between the 2 dictionaries
commonKeys = [k for k in a.keys() if k in b.keys()]

# Loop on these common keys
for k in commonKeys:
    # Update result:
    # - if the value is identical between the 2 dictionaries
    # - and if current result is lower than this value
    if a[k] == b[k]:
        if ((result == None) or (result < a[k])):
            result = a[k]

# Display result value ("None" if not found)
print(result)

Upvotes: 1

spadarian
spadarian

Reputation: 1624

In python3:

max([k1 for (k1, v1), (k2, v2) in zip(a.items(), b.items()) if v1 == v2])

Upvotes: 4

Related Questions