Home > Software engineering >  Checking which key has the most letters in its dictionary in Python
Checking which key has the most letters in its dictionary in Python

Time:09-22

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.

CodePudding user response:

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.

CodePudding user response:

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

longest = 0
word = ''
for i in range(len(keys)):
    if len(S[f'{keys[i]}']) > longest and S[f'{keys[i]}'] != 'omicron':
        longest = len(S[f'{keys[i]}'])
        word = keys[i]
print(longest, word)

Output:

5 x6
  • Related