Python - Find longest (most words) key in dictiona

2019-05-22 22:42发布

问题:

Is there a way to quickly query a dictionary object in order to find the key (all keys are of string 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

回答1:

max of - count of words per key:

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


回答2:

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)


回答3:

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


回答4:

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


回答5:

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.



回答6:

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.


回答7:

No shortcut. Simple way:

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