Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find longest (string) key in dictionary

Tags:

python

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

Example input:

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

Output:

10
like image 796
Framester Avatar asked Jun 05 '12 10:06

Framester


2 Answers

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

or

>>> max(map(len, d))
like image 135
eumiro Avatar answered Sep 22 '22 19:09

eumiro


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
like image 45
schlamar Avatar answered Sep 20 '22 19:09

schlamar