2012-08-10 29 views
1

可能重复:
Find longest (string) key in dictionary获得一个键的顶部长度在Python

不折叠。例如:

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()))) 

有没有什么方法可以在字典中获得最长的密钥长度(最好是在一行中)?这没有什么错折,但我如果有另一种方式来做到这一点在Python 3

回答

6

你可以简单地做

max(map(len, my_dict)) 

这将需要所有密钥的长度和获取最大的只是有兴趣这些长度。

为了获得最长的密钥本身,使用

max(my_dict, key=len)