Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List as value in dictionary, get key of longest list

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.

like image 1000
ustroetz Avatar asked Nov 07 '13 19:11

ustroetz


People also ask

Can you have a list as a value in a dictionary?

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.

How do you find the key with a maximum value in a dictionary?

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.

Can you use LEN () on a dictionary?

To determine how many items (key-value pairs) a dictionary has, use the len() method.

How do I get a list of key values in a dictionary?

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.


1 Answers

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]
like image 88
Ashwini Chaudhary Avatar answered Nov 03 '22 01:11

Ashwini Chaudhary