Benjy Kessler
Benjy Kessler

Reputation: 7626

Finding maximal length value in dictionary

I have a dictionary of the form {'a': [1, 2, 3], 'b': [1, 2, 3, 4], 'c': [13. 11]}. I want to find the length of the longest value in the dict. In this case that will be 4. I know how to do this with an array as follows:

maxSoFar = 0;
for key in dict.keys():
  if dict[key] > maxSoFar :
    maxSoFar = len(dict[key])

My question is, is there a magic one liner to do this?

Upvotes: 0

Views: 102

Answers (3)

vaultah
vaultah

Reputation: 46533

Yes, using max function

max(len(l) for l in dict.values()) # 4

Upvotes: 6

YXD
YXD

Reputation: 32511

How about

max(dict.values(), key=len)

Upvotes: 2

Valentin Lorentz
Valentin Lorentz

Reputation: 9753

Here:

max(map(len, dict.values()))

Upvotes: 2

Related Questions