Get the keys corresponding to the 5 smallest values within a dictionary

Viewed 32

If I have a Python dictionary, how do I get and return the keys corresponding to the 5 smallest values?

Given the input:

employees = {'any': 5, 'restraint': 8, 'shadow': 6, 'authority': 8, 'being': 6, 'now': 5, 'passed': 5, 'away': 5, 'they': 6, 'living': 6, 'together': 7}
1 Answers

Check this solution:

employees = {'any': 5, 'restraint': 8, 'shadow': 6, 'authority': 8, 'being': 6, 'now': 5, 'passed': 5, 'away': 5, 'they': 6, 'living': 6, 'together': 7}

employees_list = [(k, v) for k, v in employees.items()]
employees_list.sort(key=lambda s: s[1])
keys = [i[0] for i in employees_list[:5]]

So basically what is happening:

employees_list = [(k, v) for k, v in employees.items()]

convert the dictionary to a list of tuples:

[('any', 5), ('restraint', 8), ('shadow', 6), ('authority', 8), ('being', 6), ('now', 5), ('passed', 5), ('away', 5), ('they', 6), ('living', 6), ('together', 7)]

then sorting the list elements depending on the second element:

employees_list.sort(key=lambda s: s[1])

resulting:

[('any', 5), ('now', 5), ('passed', 5), ('away', 5), ('shadow', 6), ('being', 6), ('they', 6), ('living', 6), ('together', 7), ('restraint', 8), ('authority', 8)]

then extracting the first 5 keys.

Related