开发者

Python - Find longest (most words) key in dictionary

Is there a way to quickly query a dictionary object in order to find the key (all keys are of s开发者_StackOverflow社区tring type) with the most words?

I.e., if the item with the largest key had five words {'this is the largest key': 3}, how could I quickly query the dict and have the int '5' returned?

Best, Georgina


This will give you the key:

max(d, key=lambda x: len(x.split()))

And if you want the size:

max(len(x.split()) for x in d)


max of - count of words per key:

max(len(k.split()) for k in d.keys())


longest=max(d.keys(), key=lambda s:len(s.split()))
len(longest.split())


max(len(i.split()) for i in d.iterkeys())


The answer is no.

If you want to know if there are solutions that are fast to type, then, sure, check out the other replies. But none of them will run quickly on large dictionaries, which I believe was the spirit of your question.

If this is really something you need to do often, you should modify the points in your code that add and remove keys from your dictionary so that they also maintain a heap of keys, sorted by their word count.


If you can guarantee that...

  • there are no leading or trailing spaces
  • words are separated by exactly one space

Count

max(key.count(' ') for key in d) + 1
  • Almost zero new objects allocated, an iter and some ints
  • This uses less memory and is almost twice as fast as the those that use split.

If you can't....

Split

max(len(key.split()) for key in d)
  • Accepts irregular key values
  • Even though 1/2 as fast as the count method, it isn't slow.


No shortcut. Simple way:

import re
max([len(re.split('\s+', k)) for k in d.keys()])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜