how to sort a dictionary 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: python dict sort by value

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 3: python sort dict by key

A={1:2, -1:4, 4:-20}
{k:A[k] for k in sorted(A)}

output:
{-1: 4, 1: 2, 4: -20}

Example 4: sort the dictionary in python

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

Example 5: python get dictionary keys sorted by value

sorted(A, key=A.get)

Example 6: how to sort a dictionary

markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist = sorted(markdict.items(), key=lambda x:x[1])
sortdict = dict(marklist)
print(sortdict)

Tags:

Misc Example