Sort a dictionary by key

EasyDictionary Programs · 11 of 94

Write a Python program to sort a dictionary by its keys.

Advertisement
Input
{"d": 21, "b": 53, "a": 13, "c": 41}
Output
('a', 13)
('b', 53)
('c', 41)
('d', 21)
{'a': 13, 'b': 53, 'c': 41, 'd': 21}

Approach

  1. sorted(d.items()) sorts the pairs by key.

Solution

Python
d = {"d": 21, "b": 53, "a": 13, "c": 41}for pair in sorted(d.items()):    print(pair)print(dict(sorted(d.items())))
Output
('a', 13)
('b', 53)
('c', 41)
('d', 21)
{'a': 13, 'b': 53, 'c': 41, 'd': 21}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs