简体   繁体   中英

How would you find the most common word in a dict?

I am writing a function that takes a dictionary as a parameter and returns a key whose value is the longest by iterating over the dictionary. If the dictionary is empty it should return an empty string. If there is a tie for the word with the longest list of positions then the function may return any one of the common words.

For example:

>>> {'He': [0], 'thought': [1, 5, 6], 'it': [2], 'was': [3], 'chicken': [4]} 
Output: thought

It must return the most common word based on the positions.

However I think I get the idea but I instead a wrote a function that returns the maximum value:

def commonest(dct):
    max_length = 0
    for key, val in dct.items():
        if len(val) >= max_length:
            max_key = key
    return max_key

So instead of returning "thought" it returns "chicken". Does anyone have any suggestions?

You simply forgot to update max_length aswell:

def commonest(dct):
    max_length = 0
    for key, val in dct.items():
        if len(val) >= max_length:
            max_key = key
            max_length = len(val)
    return max_key

You can use the max function over the dict items with a key function that returns the length of the sub-list:

max(dct.items(), key=lambda t: len(t[1]))[0]

This returns: thought

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM