Find longest (string) key in dictionary

前端 未结 3 1358
野趣味
野趣味 2020-12-19 12:49

This question is similar to Python - Find longest (most words) key in dictionary - but I need the pure number of characters.

Example input:

d = {\'gr         


        
相关标签:
3条回答
  • 2020-12-19 13:35
    >>> d = {'group 1': 1, 'group 1000': 0}
    >>> len(max(d, key=len))
    10
    

    This solution is the fastest but I prefer the solutions by @eumiro and @ms4py since they do not repeat the len function twice and are more pythonic imo.

    0 讨论(0)
  • 2020-12-19 13:38

    Alternative, which is as fast as @jamylak's solution and more pythonic:

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

    See comparison:

    $ 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
    
    0 讨论(0)
  • 2020-12-19 13:42
    >>> max(len(x) for x in d)
    

    or

    >>> max(map(len, d))
    
    0 讨论(0)
提交回复
热议问题