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

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

sorted(myDic.items(),reverse=True)

but it returns

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

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

1 Answers

1
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:
    print(myDic[key])