Home > Net >  sorting by lowest key in a dict (Python)
sorting by lowest key in a dict (Python)

Time:11-12

I have a dictionary: where 0 and 1 are two index and the other numbers inside the two dictionaries are the frequency of each word in a previous list of strings

letter_positions={0: {'l': 1, 'y': 2, 'm': 1, 'r': 2}, 1: {'t': 2, 'e': 1, 'n': 1, 's': 3}}

I get that by a function that return a dictionary with the most frequent character of a string by index.

Now I'm using this function to get the most frequent character for each index:

final_dict = {}
for idx, counts in letter_positions.items():
    most_popular = max(counts.items(), key=lambda v: v[1])
    final_dict[idx] = most_popular[0][0]

The problem is that in the index 0 of the dictionary the most frequent characters are 'y' and 'r', my code return me 'y' in the final_dict dictionary, but I want to get the lowest alphabetic character 'r'.

How can I edit my code or what do I have to add here

    most_popular = max(counts.items(), key=lambda v: v[1])

to perform my need? thanks

CodePudding user response:

I'd suggest to sort the dictionary by the keys:

most_popular = max(sorted(counts.items()), key=lambda v: v[1])

CodePudding user response:

You can switch to min() and change the key= function:

letter_positions = {
    0: {"l": 1, "y": 2, "m": 1, "r": 2},
    1: {"t": 2, "e": 1, "n": 1, "s": 3},
}


final_dict = {}
for idx, counts in letter_positions.items():
    most_popular = min(counts.items(), key=lambda v: (-v[1], v[0]))
    final_dict[idx] = most_popular[0][0]

print(final_dict)

Prints:

{0: 'r', 1: 's'}

CodePudding user response:

When sorting, you can add a second metric in a list (or tuple), such that elements tied for the first position will be decided by the second value:

final_dict = {}
for idx, counts in letter_positions.items():
    most_popular = max(counts.items(), key=lambda v: [v[1],-ord(v[0])])
    final_dict[idx] = most_popular[0][0]

In the code above, we use [v[1],-ord(v[0])] as the new metric to sort values. ord returns an integer representing the position of each letter in the alphabet, so ord(v[0]) will give a higher scores to letters at the beggining of the alphabet.

The output is now:

# final_dict = {0: 'r', 1: 's'}
  • Related