Sort Python Dictionary by Key or Value Python (original) (raw)

Given a dictionary in Python, the task is to sort it by key or value, either in ascending or descending order. For Example:

**Input: {'apple': 5, 'banana': 2, 'cherry': 7}
**Output: {'banana': 2, 'apple': 5, 'cherry': 7}
**Explanation: The dictionary is sorted by values in ascending order, since 2 < 5 < 7, the order becomes {'banana': 2, 'apple': 5, 'cherry': 7}.

Let's explore different methods to sort dictionary by key or value in Python.

Sorting by Value

**1. Using sorted() with lambda: This method sorts the dictionary efficiently by its values using the sorted() function and a lambda expression.

Python `

d = {'watermelon': 1, 'apple': 2, 'banana': 3}
asc = {k: v for k, v in sorted(d.items(), key=lambda item: item[1])} print(asc)

`

Output

{'watermelon': 1, 'apple': 2, 'banana': 3}

**Explanation:

**2. Using OrderedDict: This method sorts a dictionary by values and stores the result in an OrderedDict, which preserves insertion order.

Python `

from collections import OrderedDict d = {'monday': 10, 'tuesday': 9, 'wednesday': 15} res = OrderedDict(sorted(d.items(), key=lambda item: item[1])) print(res)

`

Output

OrderedDict({'tuesday': 9, 'monday': 10, 'wednesday': 15})

**Explanation:

**3. Using for loop with sorted(): This method sorts and displays dictionary values in ascending order using for loop with sorted() function.

Python `

d = {2: 56, 1: 2, 3: 323} for k, v in sorted(d.items(), key=lambda item: item[1]): print((k, v), end=" ")

`

Output

(1, 2) (2, 56) (3, 323)

**Explanation:

**4. Using NumPy: This approach uses NumPy’s argsort() for fast value-based sorting in numerical dictionaries.

Python `

import numpy as np

d = {'alex': 10, 'ben': 9, 'clara': 15, 'diana': 2, 'eva': 32}

k = list(d.keys()) v = list(d.values())

idx = np.argsort(v) res = {k[i]: v[i] for i in idx} print(res)

`

Output

{'diana': 2, 'ben': 9, 'alex': 10, 'clara': 15, 'eva': 32}

**Explanation:

Sorting by Key

**1. Using sorted() with lambda: This method sorts the dictionary by its keys using sorted() and a lambda expression.

Python `

d = {'watermelon': 1, 'apple': 2, 'banana': 3} asc = {k: v for k, v in sorted(d.items(), key=lambda item: item[0])} print(asc)

`

Output

{'apple': 2, 'banana': 3, 'watermelon': 1}

**Explanation:

**2. Using OrderedDict: This method sorts dictionary items by key and stores them in an OrderedDict.

Python `

from collections import OrderedDict

d = {'monday': 10, 'tuesday': 9, 'wednesday': 15} res = OrderedDict(sorted(d.items(), key=lambda item: item[0])) print(res)

`

**Explanation:

**3. Using for loop with sorted(): This method sorts and prints dictionary items using key-based sorting.

Python `

d = {2: 56, 1: 2, 3: 323} for k, v in sorted(d.items(), key=lambda item: item[0]): print((k, v), end=" ")

`

**Explanation:

**4 Using NumPy: This method sorts the dictionary by converting keys to a NumPy array and using argsort() to get their sorted order.

Python `

import numpy as np

d = {'alex': 10, 'ben': 9, 'clara': 15, 'diana': 2, 'eva': 32}

k = list(d.keys()) v = list(d.values())

idx = np.argsort(k)
res = {k[i]: v[i] for i in idx}

print(res)

`