Sort dictionary by key and value

people = {3: "Jim", 2: "Jack", 4: "Jane", 1: "Jill"}

key_sorted = dict(sorted(people.items()))
print(f"{key_sorted   = }")

value_sorted = dict(sorted(people.items(), key=lambda item: item[1]))
print(f"{value_sorted = }")

Output

k v e a y l _ u s e o _ r s t o e r d t e d = = { { 1 2 : : ' ' J J i a l c l k ' ' , , 2 4 : : ' ' J J a a c n k e ' ' , , 3 1 : : ' ' J J i i m l ' l , ' , 4 : 3 : ' J ' a J n i e m ' ' } }

Sort a list of dictionaries

The next set of everyday list tasks is sorting. Depending on the data type of the items included in the lists, we’ll follow a slightly different way to sort them. Let’s first start with sorting a list of dictionaries.

dicts_lists = [
    {
        "Name": "James",
        "Age": 20,
    },
    {
        "Name": "May",
        "Age": 14,
    },
    {
        "Name": "Katy",
        "Age": 23,
    },
]

# There are different ways to sort that list
# 1 - Using the sort/ sorted function based on the name or age
dicts_lists.sort(key=lambda item: item.get("Name"))
print(dicts_lists)
dicts_lists.sort(key=lambda item: item.get("Age"))
print(dicts_lists)

# 2 - Using itemgetter module based on name
from operator import itemgetter

f = itemgetter("Name")
dicts_lists.sort(key=f)
print(dicts_lists)

Output

[ [ [ { { { ' ' ' N N N a a a m m m e e e ' ' ' : : : ' ' ' J M J a a a m y m e ' e s , s ' ' , ' , A ' g ' A e A g ' g e : e ' ' : 1 : 4 2 } 2 0 , 0 } } , { , ' { N { ' a ' N m N a e a m ' m e : e ' ' : ' : J ' a ' K m K a e a t s t y ' y ' , ' , , ' ' A ' A g A g e g e ' e ' : ' : : 2 2 0 2 3 } 3 } , } , , { { ' { ' N ' N a N a m a m e m e ' e ' : ' : : ' ' K ' M a M a t a y y y ' ' ' , , , ' ' ' A A A g g g e e e ' ' ' : : : 1 2 1 4 3 4 } } ] ]

Sort a list based on another list

Sometimes, we may want or need to use one list to sort another. So, we’ll have a list of numbers (the indexes) and a list that I want to sort using these indexes

a = ['blue', 'green', 'orange', 'purple', 'yellow']
b = [3, 2, 5, 4, 1]

#Use list comprehensions to sort these lists
sortedList =  [val for (_, val) in sorted(zip(b, a), key=lambda x: x[0])]

Output

[ ' y e l l o w ' , ' g r e e n ' , ' b l u e ' , ' p u r p l e ' , o r a n g e ' ]