Python - Sorting dictionary keys in Python 3.X


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! 
#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 
for k in Ks: print(k, D[k])              # 2.X: omit outer parens in prints 


D = {'a': 1, 'b': 2, 'c': 3} 
print( D )# from  w ww  .  java 2s.  c  om

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


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


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


Related Topic