简体   繁体   中英

How do I find the key of maximum element in a dictionary in Python language?

I have a problem since 10 days I tried to find the solution on books and internet but could not find it. Here there is an example:

animals = { 'a': ['lion'], 'b': ['baboon'], 'c': ['goat']}
animals['d'] = ['donkey']
animals['d'].append('elephant')
animals['d'].append('swan')

and I have to write a method largest to find out the key being associated to the longest list. In the example the output should be

largest(animals)
'd'

Use max() built-in with custom function used for comparisons between keys.

animals = { 'a': ['lion'], 'b': ['baboon'], 'c': ['goat']}
animals['d'] = ['donkey']
animals['d'].append('elephant')
animals['d'].append('swan')

largest = max(animals, key=lambda k: len(animals[k]))

Using key argument to max function allows to change a criteria by which elements are compared. In this case keys of dictionary are compared according to length of list stored under this key in dictionary animals .

Split the dictionary into 2 lists of keys and values, if your dictionary is not very large. This can be very efficient method. Then, you can find the max element using the max() function.

def largest(animals):
    keys = list(animals.keys())
    vals = list(animals.values())
    return keys[vals.index(max(vals))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM