Online Tutorials & Training Materials | STechies.com
Register Login

How to Sort a Dictionary in Python?

21 Aug 2019 10:55 am || 0

Python Sorted Dictionary

Dictionaries in Python are used to store key-value pairs in disordered (not in order) manner. You can also sort or order dictionary in ascending /descending order using built-in python function sorted().

  • Python sort dictionary by key
  • Sort dictionary by value python

Python Sort Dictionary by key

In this example we are using a sorted() function to sort the dictionary and for loop to print the item of the dictionary.

Example 1:

# Python3
# Sort or Order dictionary with key-value pairs.

# Initialized a dictionary
fruitscolor = {"Banana" : "Yellow",
    "Mango" : "Green",
    "Apple" : "Red",
    "Grapefruit" : "Pink",
    "Blackberry" : "Purple",
    "Sapodilla" : "Brown"}

# sort and print the items of dictionary
for fruit, color in sorted(fruitscolor.items()):
  print(fruit, ":", color)

Output:

Apple : Red
Banana : Yellow
Blackberry : Purple
Grapefruit : Pink
Mango : Green
Sapodilla : Brown

Example 2:

# Python3
# Sort or Order dictionary by key.

# Initialized a dictionary
fruitscolor = {"Banana" : "Yellow",
    "Mango" : "Green",
    "Apple" : "Red",
    "Grapefruit" : "Pink",
    "Blackberry" : "Purple",
    "Sapodilla" : "Brown"}

# sort items in dictionary
fruitscolor = sorted(fruitscolor)

# Print items in dictionary through for loop
for fruit in fruitscolor:
 print(fruit)

Output: 

Apple
Banana
Blackberry
Grapefruit
Mango
Sapodilla

Sort Dictionary by Value Python

To sort the dictionary by the value, we use value() function with sorted() function and to print the value we use ‘for loop’.

Example: 

# Python3
# Sort or Order dictionary by values.

# Initialized a dictionary
fruitscolor = {"Banana" : "Yellow",
    "Mango" : "Green",
    "Apple" : "Red",
    "Grapefruit" : "Pink",
    "Blackberry" : "Purple",
    "Sapodilla" : "Brown"}

# sort values in dictionary
fruitscolor = sorted(fruitscolor.values())

# Print values in dictionary through for loop
for color in fruitscolor:
  print(color)

Output:

Brown
Green
Pink
Purple
Red
Yellow

Reversing the Sort Order

To change the sort order, we need to use “reverse=True” option with sorted() function.

We can use this method to explain all of the scenarios as mentioned above, such as sort by key, sort by key-value pair & sort by value.

Dictionary sort by key or key-value pairs in reverse order

Example:

# Python3
# Sort or Order dictionary by key in reverse order.

# Initialized a dictionary
fruitscolor = {"Banana" : "Yellow",
    "Mango" : "Green",
    "Apple" : "Red",
    "Grapefruit" : "Pink",
    "Blackberry" : "Purple",
    "Sapodilla" : "Brown"}

# Sort dictionary in reverse order
fruitscolor = sorted(fruitscolor, reverse=True)

# Print items in dictionary through for loop
for fruit in fruitscolor:
 print(fruit)

Output: 

Sapodilla
Mango
Grapefruit
Blackberry
Banana
Apple