Sort a Python dictionary

A Python dictionary is a kind of set and doesn't essentially have an order. But it can be regarded as a list of tuples, and in fact, the sorted() sorts all items of a dictionary by ascending or descending and returns a sorted list.

stocks = {'Square': 136, 'Apple': 112, 'Facebook': 275}

a = sorted(stocks.items())
b = sorted(stocks.items(), reverse=True)

print(a)
# [('Apple', 112), ('Facebook', 275), ('Square', 136)]

print(b)
# [('Square', 136), ('Facebook', 275), ('Apple', 112)]

The sorted() returns a list, not dictionary. The second argument (reverse) decides the order.

Let's check the changes of "keys" or company names order.

Square, Apple, Facebook -> Apple, Facebook, Square

After sorting, company names are alphabetized. Be cautious of the argument of the sorted(). If the first argument is a dictionary itself, it returns the list of keys.

stocks = {'Square': 136, 'Apple': 112, 'Facebook': 275}

a = sorted(stocks)

print(a)
# ['Apple', 'Facebook', 'Square']

Sort a Python dictionary by value using lambda expression

From Python 3, it's possible to sort a dictionary using a lambda expression.

a = {'book': 97, 'pen': 145, 'note': 314}
b = sorted(a.items(), key=lambda x: x[1])
c = sorted(a.items(), key=lambda x: x[1], reverse=True)

print(b)  # [('book', 97), ('pen', 145), ('note', 314)]
print(c)  # [('note', 314), ('pen', 145), ('book', 97)]

The sorted() returns pairs of a dictionary's key and value. With reverse true, it sorts by descending.

Comments

Powered by Markdown

More