Home > Back-end >  How to get maximum value of one entity in nested dictionary?
How to get maximum value of one entity in nested dictionary?

Time:07-16

people = {1: {'Name': 'John', 'Age': '22', 'Sex': 'Male'}, 2: {'Name': 'Marie', 'Age': '26', 'Sex': 'Female'}, 3: {'Name': 'Marie', 'Age': '25', 'Sex': 'Female'}, 4: {'Name': 'Marie', 'Age': '21', 'Sex': 'Female'}}

I want to get the maximum value of 'Age'. Kindly help me how to do this.

CodePudding user response:

You can use max with a defined key and lambda.

people = {1: {'Name': 'John', 'Age': '22', 'Sex': 'Male'}, 2: {'Name': 'Marie', 'Age': '26', 'Sex': 'Female'}, 3: {'Name': 'Marie', 'Age': '25', 'Sex': 'Female'}, 4: {'Name': 'Marie', 'Age': '21', 'Sex': 'Female'}}
max(people.values(), key=lambda x: int(x['Age']))
# {'Name': 'Marie', 'Age': '26', 'Sex': 'Female'}

max(people.values(), key=lambda x: int(x['Age']))['Age']
# '26'

CodePudding user response:

If you wanted just the max value then max with a generator would suffice

people = {1: {'Name': 'John', 'Age': '22', 'Sex': 'Male'}, 2: {'Name': 'Marie', 'Age': '26', 'Sex': 'Female'}, 3: {'Name': 'Marie', 'Age': '25', 'Sex': 'Female'}, 4: {'Name': 'Marie', 'Age': '21', 'Sex': 'Female'}}
result = max(int(p['Age']) for p in people.values())

Which I prefer over the lambda, however if you want the dictionary that has the max Age then @I'mahdi answer is what you want.

  • Related