Python Practice › Dictionary Programs › Program 11
Sort a dictionary by key
Write a Python program to sort a dictionary by its keys.
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
sorted(d.items())sorts the pairs by key.
Solution
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}Learn the concept
New to this topic? Read the lesson, then come back.