How To Sort Python Dictionary By Value?

We have a dictionary which is read from a file. One field is string other field is number. String fields are unique and used as keys. Sorting by keys is easy but how can we sort them by values

Our Dictionary

We have the following dictionary which is consist of string and numbers.

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Our Dictionary
Our Dictionary

By the way, we are using python interpreter to make things more interactive and easy

Sort Them By Value

We will sort them by value and create a list of tuples

sorted_x = sorted(x.items(), key=operator.itemgetter(1))
Sort Them By Value
Sort Them By Value

And The Whole Code

We will have following a full script which can sort the given dictionary by value.

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))

1 thought on “How To Sort Python Dictionary By Value?”

Leave a Comment