Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Showing the max key:value Dictionaries inside a list

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading