How to sort dictionary keys by alphabetical order (create an ordered dictionary) in python ?


Examples of how to sort dictionary keys by alphabetical order (create an ordered dictionary) in python:

Create a dictionary in python

Let's create a simple dictionary

d = {'a':1,'c':3,'b':2,'d':4,'f':6,'e':5}

print(d)

returns

{'a': 1, 'c': 3, 'b': 2, 'd': 4, 'f': 6, 'e': 5}

and

for k,v in d.items():
    print(k,v)

returns

a 1
c 3
b 2
d 4
f 6
e 5

Sort an existing dictionary by alphabetical order

To sort an existing dictionary :

from collections import OrderedDict

new_d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))

print(new_d)

returns

OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6)])

and

for k,v in new_d.items():
    print(k,v)

returns

a 1
b 2
c 3
d 4
e 5
f 6

Use pprint

Note: if your goal is to print a dictionary in alphabetical order, a quick and easy solution is to use pretty printer pprint

import pprint

d = {'a':1,'c':3,'b':2,'d':4,'f':6,'e':5}

pp = pprint.PrettyPrinter(indent=1, width=10)
pp.pprint(d)

returns

{'a': 1,
 'b': 2,
 'c': 3,
 'd': 4,
 'e': 5,
 'f': 6}

References