dic = {'Tea': 35, 'Coffee': 35, 'Chocolate': 10}
I want to sort this dictionary by values in descending order, but how can I access keys too?
Sample Code:
for x in sorted(dic.values()):
print(key, dic[key])
I’d also like the output to be sorted alphabetically by key when the values are equal.
Expected Output:
Coffee 35
Tea 35
Chocolate 10
What you want is the
dict.items()method, which provides(key, value)tuples.To sort by the value, you then use a
keymethod, in this case, anoperator.itemgetter()to take the second value from the tuple for sorting, then set thereverseattribute to get them in the order you want.Edit: If you want to sort by key as a secondary sort, we can simply pass a tuple of values, and Python will sort on the first value, then the second, etc… The only issue is using reverse will mean we get them in the wrong order. As a hack, we simply use the negative version of the value to sort without reverse: