Search code examples
pythondictionarykey

Checking which key has the most letters in its dictionary in Python


I have a dictionary in a Python code like this:

S = {(x0): 'omicron', (x1): 'a', (x2): 'ab', (x3): 'abbr', (x4): 'abr', (x5): 'abrf', (x6): 'abrfa', (x7): 'af', '(x8)': 'afc'}

I would like to check which key has its corresponding dictionary with the highest numer of letters, except for the one that has 'omicron'. The answer in this example should be: (x6), because it has a dictionary with 5 letters, more than any other key, and not counting (x0):'omicron'.

Is there an efficient way to do this? Thank you.


Solution

  • You could use the key parameter of max:

    res = max(S, key=lambda x: (S[x] != 'omicron', len(S[x])))
    print(res)
    

    Output

    (x6)
    

    This will make the keys that the value is different than 'omicron' have a higher value than one that are equals (1 > 0). For those keys that do not have 'omicron' value use the length as a tie-breaker.