w3resource

Python pprint Exercise - Sort the keys of a dictionary before printing it using the pprint module


2. Sorted Keys with Pprint

Write a Python program to sort the keys of a dictionary before printing it using the pprint module.

Sample Solution:

Python Code:

import pprint

colors = {
    'Red': 10,
    'Green': 20,
    'White': 30,
    'Black': 40,
    'Blue': 50,
    'Orange': 70
  }
print("Sort the keys of a dictionary before printing it:")
pprint.pprint(colors, sort_dicts=True)
nested_dict = {
    'd1': {
        'a': 1,
        'c': 2,
        'b': 3
    },
    'd2': {
        'f': 4,
        'e': 5,
        'd': 6
    },
    'd3': {
        'g': 7,
        'h': 8,
        'i': 9
    }
}
print("\nSort the keys of a nested dictionary before printing it:")
pprint.pprint(nested_dict, sort_dicts=True)

Sample Output:

Sort the keys of a dictionary before printing it:
{'Black': 40, 'Blue': 50, 'Green': 20, 'Orange': 70, 'Red': 10, 'White': 30}

Sort the keys of a nested dictionary before printing it:
{'d1': {'a': 1, 'b': 3, 'c': 2},
 'd2': {'d': 6, 'e': 5, 'f': 4},
 'd3': {'g': 7, 'h': 8, 'i': 9}}

Flowchart:

Flowchart: Sort the keys of a dictionary before printing it using the pprint module.

For more Practice: Solve these Related Problems:

  • Write a Python program that creates a dictionary with unsorted keys and prints it with pprint after sorting the keys alphabetically.
  • Write a Python function that accepts a dictionary and uses pprint with the sort_dicts parameter set to True (or sorted keys manually) to display the dictionary sorted by keys.
  • Write a Python script to generate a dictionary from user input, then pretty-print it with keys sorted, and compare the output with the unsorted version.
  • Write a Python program to combine two dictionaries, then use pprint to display the resulting dictionary with sorted keys and verify the order.

Go to:


Previous: Print a dictionary, nested dictionary using the pprint module.
Next: Specify the width of the output while printing a list, dictionary.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.