小编典典

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

python

这个问题与Python类似-在字典中查找最长(最多单词)键-但我需要纯字符数。

输入示例:

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

输出:

10

阅读 293

收藏
2021-01-20

共1个答案

小编典典

替代方法,与@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
2021-01-20