How To Sort By Value A Python Dictionary? – POFTUT

How To Sort By Value A Python Dictionary?


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

Example 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}

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))

Complete Dictionary Sort Example

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))

LEARN MORE  Memcached Get Check and Set Operation

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

Leave a Comment