ragardner
ragardner

Reputation: 1975

Fastest way to determine the length of longest string for a column across lists

I have a dictionary with 5000 keys who's values are lists, I need to determine quickly the length of the longest string for a given index in all of the dictionary values

index = 1
d = {'foo': ['abc', 'defg'],
     'bar': ['hij', 'klmno']}
#m = len(max(d.values()[index],key=len))?

expected output: 5, because of all of the values at index 1 ('defg' and 'klmno'`, the latter is the longest).

Upvotes: 1

Views: 252

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1122082

You need to use a generator expression to extract the right index:

longest_string = len(max((row[index] for row in d.values()), key=len))

If all you need is the length, not the string itself, you may as well get the length in the generator expression:

highest_length = max(len(row[index]) for row in d.values())

Demo:

>>> index = 1
>>> d = {'foo': ['abc', 'defg'],
...      'bar': ['hij', 'klmno']}
>>> max((row[index] for row in d.values()), key=len)
'klmno'
>>> max(len(row[index]) for row in d.values())
5

You can't escape having to iterate over all values in the dictionary however.

Upvotes: 5

Neil
Neil

Reputation: 14313

You're pretty close, you just need to use a generator expression to iterate over all items in the list.

print max(len(max(d[i],key=len)) for i in d)

Upvotes: -1

Mathias Rav
Mathias Rav

Reputation: 2973

First, extract all the strings of interest with a list comprehension:

xs = [v[index] for v in d.values()]

Next, take max over the lens of the strings:

print(max(map(len, xs)))

Upvotes: 1

Related Questions