Python - Sorting dictionary keys in Python 3.X

Introduction

Because keys does not return a list in Python 3.X.

D = {'a': 1, 'b': 2, 'c': 3} 
print( D )

Ks = D.keys()                            # Sorting a view object doesn't work! 
#Ks.sort() 
#AttributeError: 'dict_keys' object has no attribute 'sort' 

In Python 3.X you must either convert to a list manually or use the sorted call on either a keys view or the dictionary itself:

Ks = list(Ks)                            # Force it to be a list and then sort 
Ks.sort() 
for k in Ks: print(k, D[k])              # 2.X: omit outer parens in prints 

Demo

D = {'a': 1, 'b': 2, 'c': 3} 
print( D )# from ww  w  . j  a v  a  2 s.c  o m

Ks = D.keys()                            # Or you can use sorted() on the keys 
for k in sorted(Ks): print(k, D[k])      # sorted() accepts any iterable 
                                         # sorted() returns its result

Result

Using the dictionary's keys iterator is preferable in 3.X, and works in 2.X as well:

Demo

D = {'b': 2, 'c': 3, 'a': 1}                     # Better yet, sort the dict directly 
for k in sorted(D): print(k, D[k])       # dict iterators return keys

Result

Related Topic