How to show the max key:value Dictionaries inside a list the code shown below can only show the values.
ages = [{'Matt': 30, 'Katie': 29}, {'Nik': 31, 'Jack': 43,}, {'Alison': 32, 'Kevin': 38}]
max_age = int()
for dict in ages:
if max(dict.values()) > max_age:
max_age = max(dict.values())
ages = [{'Matt': 30, 'Katie': 29}, {'Nik': 31, 'Jack': 43,}, {'Alison': 32, 'Kevin': 38}]
max_age = int()
for dict in ages:
if max(dict.values()) > max_age:
max_age = max(dict.values())
print(max_age)
Is there any way to show the max key also with the value?
CodePudding user response:
There are three tools that make short work of this problem.
- The
max()
function with a key argument selects the largest input according to the criteria in the key-function. - The
itemgetter(1)
function extracts the second value in a tuple. - A list comprehension takes care of looping and accumulating the results.
This leads to simple and elegant code:
>>> from operator import itemgetter
>>> [max(m.items(), key=itemgetter(1)) for m in ages]
[('Matt', 30), ('Jack', 43), ('Kevin', 38)]
CodePudding user response:
You can use max
with key
parameter:
ages = [{'Matt': 30, 'Katie': 29}, {'Nik': 31, 'Jack': 43}, {'Alison': 32, 'Kevin': 38}]
max_name, max_age = max((name_age for dct in ages for name_age in dct.items()), key=lambda x: x[1])
print(max_name) # Jack
print(max_age) # 43
Specifically, it first converts the list of dicts into a list of tuples:
print([name_age for dct in ages for name_age in dct.items()])
# [('Matt', 30), ('Katie', 29), ('Nik', 31), ('Jack', 43), ('Alison', 32), ('Kevin', 38)]
Then max(..., key=lambda x: x[1])
finds the maximum with respect to the second item of each tuple.