Reputation: 81
Basically I have been tasked with outputting the max and min values of this list: {"a": 43, "b": 1233, "c": 8}, where the correct output should be
min: c
max: b
While I have already solved this, I have learned that another solution is much more concise:
print('min:', min(test_dict, key=test_dict.get))
print('max:', max(test_dict, key=test_dict.get))
Main problem faced here is that I don't understand how the min and max functions work like that, shouldn't its arguments only take in integers? Also what is key = test_dict.get?
Upvotes: 0
Views: 236
Reputation: 953
You want to use ".values()", otherwise it defaults to keys
dict={"a": 43, "b": 1233, "c": 8} print(max(dict.values()))
Upvotes: 0
Reputation: 226
key is a parameter of the min/max function, which makes python know how to compare two element in test_dict.
test_dict.get
is a function, and it receives one parameter key, and returns the value in test_dict. So when the min
or max
function compares two element, for example, "a" & "b":
Hence "a"<"b".
Upvotes: 1
Reputation: 781741
The first argument can be a sequence of any type of data.
min
and max
will iterate over the elements of the sequence, calling the key
function on each of them, and then return the element where the value of the function is minimized or maximized.
When you iterate over a dictionary, the elements are the dictionary keys. test_dict.get(x)
returns the element of test_dict
whose key is x
.
So min(test_dict, key=test_dict.get)
will iterate over the keys of test_dict
, and for each of them it will call test_dict.get()
, which returns an integer. It will then return the key with the minimum value.
Upvotes: 1