How to sor a dictionary by key?

Asked by At

I want to sort my dictionary by key only but I failed.

My dictionary is



but it returns

{'a': {}, 'c': {}, 'b': {}}

but I want {'c': {}, 'b': {}, 'a': {}} sort by descending order

1 Answers

N Chauhan On

sorted will always return a list. You can’t have sorted dictionaries as before Python 3.6, dictionaries have no order.

You seem to have forgotten to assign your value to a variable:

myDic = {{'a':{},'b':{},'c':{}}
sorted_keys = sorted(myDic, reverse=True)

I didn’t sort myDic.items() as we only need to sort the keys into a list.

Now when you want to loop over the dictionary ‘in order’, iterate over the list of sorted keys and get the corresponding value from the dictionary:

for key in sorted_keys: