Python - Sort Dictionary Key and Values List
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.
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:
- sorted(t) sorts dictionary keys in ascending order.
- {key: sorted(t[key]) ...} creates a new dictionary with each list of values sorted.
Using Lambda Function with sorted()
This method sorts dictionary items using a lambda function, then sorts the lists of values for each key.
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:
- sorted(t.items(), key=lambda x: x[0]): Sorts items by key.
- dict(...): Converts sorted pairs back to a dictionary.
- res[key] = sorted(res[key]): Sorts each value list.
Using zip() with sorted()
This method zips dictionary keys and values into tuples, sorts them by key, and then reconstructs the dictionary.
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:
- zip(keys, values): Pairs each key with its list.
- sorted(..., key=lambda x: x[0]): Sorts key-value pairs by key.
- {k: sorted(v) for k, v in s1}: Rebuilds a sorted dictionary.
Using Recursive Method
This approach recursively finds and sorts the smallest key and its corresponding list, then processes the remaining dictionary.
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)
Output
{'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]}
Explanation:
- min(t.keys()): Finds the smallest key.
- sorted(t[m1]): Sorts the value list for that key.
- Recursively sorts remaining keys until the dictionary is empty.