-1

I've already seen several posts about dictionary of lists but none of them could help me so far. I have a dictionary of lists like:

dict = {'a': [1,5,4], 'b': [4], 'c': [1,5,4,3,8], 'd': [1,4]}

Now I want, in a loop, get the list with more elements, in this case the first list would be the "c" and next remove that list and start the loop again. I started by append the keys and the values of "dict" in a array (I don't know if this is necessary):

for key, value in dict.items():
    array_keys.append(str(key))
    array_values.append(dict[key])

Next, I tried to start the loop and to get the list with more elements I used:

max_list = max([len(i) in array_values])

With this I get "5" that is the maximum number of elements of values in the dictionary. I want to get the name of list, "c". Can you help me?

digs_ef
  • 11
  • 3

1 Answers1

4

Use max() with a key function:

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

This returns the key for which the value is longest.

Normally max() will compare the values of the iterable you give it, returning the element that'd be sorted last. If you pass a key function along, it'll return the value where key(value) will sort last. Here the key function returns the length of the value associated with the dictionary key.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343