python dictionary sort code example

Example 1: how can I sort a dictionary in python according to its values?

s = {1: 1, 7: 2, 4: 2, 3: 1, 8: 1}
k = dict(sorted(s.items(),key=lambda x:x[0],reverse = True))
print(k)

Example 2: 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 3: sort dictionary by value python

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
{k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}

Example 4: sort the dictionary in python

d = {2: 3, 1: 89, 4: 5, 3: 0}
od = sorted(d.items())
print(od)

Example 5: sort a dictionary

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

Example 6: dict sort

[(k,di[k]) for k in sorted(di.keys())]

Tags: