Python Sort Dictionary Key and Values List (original) (raw)

Given a dictionary containing keys and corresponding lists as values, the task is to sort both the dictionary keys in ascending order and the lists of values for each key. For Example:

**Input: {'c': [3], 'b': [12, 10], 'a': [19, 4]}
**Output: {'a': [4, 19], 'b': [10, 12], 'c': [3]}

Let's explore different methods to sort dictionary key and values list in Python.

Using Dictionary Comprehension + sorted()

This method combines both key sorting and value list sorting in a single line using dictionary comprehension.

Python `

t = {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} res = {key: sorted(t[key]) for key in sorted(t)} print(res)

`

Output

{'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]}

**Explanation:

Using Lambda Function with sorted()

This method sorts dictionary items using a lambda function, then sorts the lists of values for each key.

Python `

t = {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} res = dict(sorted(t.items(), key=lambda x: x[0]))

for key in res: res[key] = sorted(res[key]) print(res)

`

Output

{'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]}

**Explanation:

Using zip() with sorted()

This method zips dictionary keys and values into tuples, sorts them by key, and then reconstructs the dictionary.

Python `

t = {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} keys = list(t.keys()) values = list(t.values())

s1 = sorted(zip(keys, values), key=lambda x: x[0]) res = {k: sorted(v) for k, v in s1}

print(res)

`

Output

{'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]}

**Explanation:

Using Recursive Method

This approach recursively finds and sorts the smallest key and its corresponding list, then processes the remaining dictionary.

Python `

def sort_dict(t): if not t: return {} m1 = min(t.keys()) s1 = sorted(t[m1]) remaining = {k: v for k, v in t.items() if k != m1} return {m1: s1, **sort_dict(remaining)}

t = {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} res = sort_dict(t) print(res)

`