Georgina
Georgina

Reputation: 391

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 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

Answers (7)

nate c
nate c

Reputation: 9005

max of - count of words per key:

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

Upvotes: 1

kevpie
kevpie

Reputation: 26098

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.

Upvotes: 0

jtdubs
jtdubs

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

mshsayem
mshsayem

Reputation: 18008

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

Upvotes: 0

Kabie
Kabie

Reputation: 10663

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

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

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

dkamins
dkamins

Reputation: 21918

No shortcut. Simple way:

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

Upvotes: -1

Related Questions