在字典中查找最长(字符串)键

时间:2012-06-05 10:22:54

标签: python

这个问题类似于Python - Find longest (most words) key in dictionary - 但我需要纯粹的字符数。

示例输入:

d = {'group 1': 1, 'group 1000': 0}

输出:

10

3 个答案:

答案 0 :(得分:12)

>>> max(len(x) for x in d)

>>> max(map(len, d))

答案 1 :(得分:9)

>>> d = {'group 1': 1, 'group 1000': 0}
>>> len(max(d, key=len))
10

这个解决方案是最快的,但我更喜欢@eumiro和@ ms4py的解决方案,因为它们不重复len函数两次并且更加pythonic imo。

答案 2 :(得分:9)

替代方案,这与@jamylak的解决方案一样快,而且更加pythonic:

from itertools import imap
max(imap(len, d))

见比较:

$ python -m timeit -s "d = {'group 1': 1, 'group 1000': 0}" "len(max(d,key=len))"
1000000 loops, best of 3: 0.538 usec per loop

$ python -m timeit -s "d = {'group 1': 1, 'group 1000': 0}" "max(len(x) for x in d)"
1000000 loops, best of 3: 0.7 usec per loop

$ python -m timeit -s "d = {'group 1': 1, 'group 1000': 0}; from itertools import imap" \
  "max(imap(len, d))"
1000000 loops, best of 3: 0.557 usec per loop