Give a dictionary like this
testDict = {76: [4], 32: [2, 4, 7, 3], 56: [2, 58, 59]}
How do I get the key of the longest list? In this case it would be 32
.
For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.
By using max() and dict. get() method we can easily get the Key with maximum value in a dictionary. To obtain the maximum value from the dictionary we can use the in-built max() function. In this example, we can use iterable and dict to get the key paired with the maximum value.
To determine how many items (key-value pairs) a dictionary has, use the len() method.
Using Iterable Unpacking Operator Alternatively, you can call the dict. keys() function to make your code more explicit. To get a list of the dictionary's values, you can call the dict. values() function.
Use max
:
>>> max(testDict, key=lambda x:len(testDict[x]))
32
If multiple keys contain the longest list:
I want to get multiple keys then.
>>> testDict = {76: [4], 32: [2, 4, 7, 3], 56: [2, 58, 59], 10: [1, 2, 3, 4]}
>>> mx = max(len(x) for x in testDict.itervalues())
>>> [k for k, v in testDict.iteritems() if len(v)==mx]
[32, 10]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With