python sort array of dictionary by value code example

Example 1: how to sort a dictionary by value in python

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


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

Example 2: Python sort dictionary by value

from operator import itemgetter
new_dict = sorted(data.items(), key=itemgetter(1))

Example 3: python sort array of dictionary by value

my_list = sorted(my_list, key=lambda k: k['name'])

Tags:

Misc Example