user5282752
user5282752

Reputation:

How to compare values between key value pairs in a dictionary of python?

My plan is to take every value in a python dict, so I have done that.

data = {}
for _ in range(int(input())):
    n = input()
    s = float(input())
    data.update({n: s})


>>> 2
>>> harry
>>> 2
>>> barry
>>> 3
>>> {'harry': 2.0, 'barry': 3.0}

now I want to compare the VALUES in this dict and return the result of max-min. How could i do this ?

thanks in advance

Upvotes: 0

Views: 570

Answers (2)

abarnert
abarnert

Reputation: 365657

You can get the values of a dict with data.values(). That gives you a perfectly good iterable that you can pass to max or min:

>>> data = {'harry': 2.0, 'barry': 3.0}
>>> max(data.values())
3.0

Or you can get the key-value pairs with data.items(), and pass the result to max or min with a key function that compares on the second part of the pair instead of the first:

>>> max(data.items(), key=lambda kv: kv[1])
('barry', 3.0)

Or, instead of writing the key function manually, you can use operator.itemgetter to do it for you:

>>> max(data.items(), key=operator.itemgetter(1))
('barry', 3.0)

Or you can get the keys (either with data.keys(), or just using data itself as the iterable—dictionaries are iterables of their keys), and use the dict's data.get method as your key function:

>>> max(data, key=data.get)
'barry'

Or, if you need to do a lot of these value-based searches, you might want to create a reverse dictionary:

>>> revdata = {value: key for key, value in data.items()}
>>> max(revdata)
3.0
>>> max(revdata.items())
(3.0, 'barry')

Upvotes: 2

Reut Sharabani
Reut Sharabani

Reputation: 31339

If you want just the values:

min_value = min(data.values())
max_value = max(data.values())

If you want the key (getting the value later is easy):

min_key = min(data, key=data.get)  # key=data.__getitem__ will also work
max_key = max(data, key=data.get)

Upvotes: 3

Related Questions