Python Program To Sort Dictionary

01. Example

Using the key of dictionary.

data = {
  "One": 1,
  "Two" : 2 ,
  "Three" : 3,
  "Four" : 4
}

for key in sorted(data.keys()) :
    print(key, "t : " , data[key])

Output:

Four    :  4
One    :  1
Three    :  3
Two    :  2

02. Example

Using the values of dictionary.

data = {
  "One": 1,
  "Two" : 2 ,
  "Three" : 3,
  "Four" : 4
}

for element in sorted(data.items()) :
    print(element[0] , "t :" , element[1] )

Output:

Four    :  4
One    :  1
Three    :  3
Two    :  2

Leave a comment