Reputation: 391
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
Upvotes: 2
Views: 4308
Reputation: 9005
max of - count of words per key:
max(len(k.split()) for k in d.keys())
Upvotes: 1
Reputation: 26098
If you can guarantee that...
Count
max(key.count(' ') for key in d) + 1
If you can't....
Split
max(len(key.split()) for key in d)
Upvotes: 0
Reputation: 13973
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.
Upvotes: 0
Reputation: 10663
longest=max(d.keys(), key=lambda s:len(s.split()))
len(longest.split())
Upvotes: 1
Reputation: 798686
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)
Upvotes: 3
Reputation: 21918
No shortcut. Simple way:
import re
max([len(re.split('\s+', k)) for k in d.keys()])
Upvotes: -1