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?
>Solution :
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.