Frage

Possible Duplicate:
Find longest (string) key in dictionary

Without folding. Example:

from functools import reduce
dict = {'t1': 'test1', 'test2': 't2'}
print(len(reduce(lambda x, y: x if len(x) >= len(y) else y, dict.keys())))

Is there any way to get the longest key's length in a a dictionary (preferably in one line)? There's nothing wrong with folding but I'm just interested if there's another way to do it in Python 3.

War es hilfreich?

Lösung

You can simply do

max(map(len, my_dict))

This will take the lengths of all keys and extract the maximum of these lengths.

To get the longest key itself, use

max(my_dict, key=len)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top