Python - Dictionary Sorting Keys: for Loops

Introduction

Grab a list of keys with the dictionary keys method

Sort that with the list sort method

Step through the result with a Python for loop.

Demo

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

Ks = list(D.keys())                # Unordered keys list 
print( Ks )                                 # A list in 2.X, "view" in 3.X: use list() 

Ks.sort()                          # Sorted keys list 
print( Ks )

for key in Ks:                     # Iterate though sorted keys 
    print(key, '=>', D[key])       # <== press Enter twice here (3.X print)

Result

The sorted call returns the result and sorts a variety of object types, in this case sorting dictionary keys automatically:

Demo

D = {'a': 1, 'b': 2, 'c': 3} 
print( D )# w w w  .ja v  a2s  . c o m

for key in sorted(D): 
     print(key, '=>', D[key])

Result

Related Topic