Assume that we have the following dictionary and we want to sort it by values (assume that the values are numeric data type).
d={"a":3,"b":5,"c":2} # sort it by value dict(sorted(d.items(), key=lambda item: item[1]))
{'c': 2, 'a': 3, 'b': 5}
If we want to sort it in descending order:
dict(sorted(d.items(), key=lambda item: item[1], reverse=True))
{'b': 5, 'a': 3, 'c': 2}
Finally, if we want to get the first n keys:
n = 2 dict(sorted(d.items(), key=lambda item: item[1])[0:n])
{'c': 2, 'a': 3}