How to sort dictionary by keys or by values in Python


Usually dictionary have sorted by keys. But sometimes it got messy un-sorted dictionary because using dict.update() or while adding new dict. You can sort it by keys using :

1
2
sort_dict = [x for x in messy_dict.iteritems()]
sort_dict.sort(key=lambda x: x[0]) # sort by key

Neat Way by Mr. Kholid :

by key:

1
sorted(a.items())

by value:

1
sorted(a.items(), key=lambda x: x[1])

Want more detailed explanation? Open your python console.
First, we define a dictionary :

1
a = {‘hello’: 1, ‘aa’: 2}

Then we insert new dictionary into exist dict using update() :

1
2
a.update({‘x’:3})
a.update({‘c’:4})

Then, we got a dictionary messy like this :

1
2
for x in a.iteritems():
    print(x)

This will showing result like this :

1
2
3
4
(‘aa’, 2)
(‘x’, 3)
(‘c’, 4)
(‘hello’, 1)

Now let we convert dict into a list

1
sort_dict = [x for x in a.iteritems()]

It should have result:

1
[(‘aa’, 2), (‘x’, 3), (‘c’, 4), (‘hello’, 1)]

We can get key and value in sort_dict by :

1
2
for x in sort_dict:
    print "key %s, value: %s" % (x[0], x[1])

Then we just sort it by :

1
sort_dict.sort(key=lambda x: x[0]) # sort by key

Now it will show results :

1
[(‘aa’, 2), (‘c’, 4), (‘hello’, 1), (‘x’, 3)]

How if we want to sort by value ? Then you just use x[1] right?

1
sort_dict.sort(key=lambda x: x[1]) # sort by value

And sort_dict will have results :

1
[(‘hello’, 1), (‘aa’, 2), (‘x’, 3), (‘c’, 4)]

Easy sorting dictionary in Python! 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.