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

Active March 24, 2021    /    Viewed 6529    /    Comments 0    /    Edit


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


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount