my_dictionary = {'a': 1, 'b': 3, 'f': 2, 'k': 2, 'l': 2, 'p': 2, 'g': 1}
How can I sort my_dictionary by value and if values are same then how can I sort keys by alphabet
i_want = {'b': 3, 'f': 2, 'k': 2, 'l': 2, 'p': 2, 'a': 1, 'g': 1}
my_dictionary = {'a': 1, 'b': 3, 'f': 2, 'k': 2, 'l': 2, 'p': 2, 'g': 1}
How can I sort my_dictionary by value and if values are same then how can I sort keys by alphabet
i_want = {'b': 3, 'f': 2, 'k': 2, 'l': 2, 'p': 2, 'a': 1, 'g': 1}
Try this:
# First sort base negative number ascending
# Second sort base alphabet ascending
>>> dict(sorted(dct.items(), key = lambda x: (-x[1], x[0])))
# --------------------------------------------^^^ here we can pass numbers as negative.
{'b': 3, 'f': 2, 'k': 2, 'l': 2, 'p': 2, 'a': 1, 'g': 1}