Sorting Dictionary by Key

Write a Python program to sort a dictionary by key.

Example 1:

Input: {"b": 5, "a": 3, "c": 2} 
Output: {"a": 3, "b": 5, "c": 2}

Example 2:

Input: {"x": 7, "z": 2, "y": 1} 
Output: {"x": 7, "y": 1, "z": 2}

Use the built-in sorted() function in combination with the items() method of the dictionary.

def sort_dict(d):
    return dict(sorted(d.items()))

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!