Python dictionaries are not ordered by default, this example helps you to sort a python dictionary by key.
How to sort Python dictionary by key?
Even if you sort the dict using sorted()
function, you wouldn’t be able to store them in another dict as because the dictionary does not preserve the order by default. Here the Python collections.OrderedDict()
function helps you to preserve the order of the items.
collections.OrderedDict():
Sorting numbers.
import collections
if __name__ == '__main__':
data = {1: 'one', 3: 'three', 4: 'four', 2: 'two'}
print("Before sort")
print(data)
orderd_dict = collections.OrderedDict(sorted(data.items()))
print("After sort")
print(orderd_dict)
Output:
Before sort
{1: 'one', 3: 'three', 4: 'four', 2: 'two'}
After sort
OrderedDict([(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')])
we can even sort the sting keys using collections.orderedDict() function
import collections
if __name__ == '__main__':
data = {'one': 1, 'three': 3, 'two': 2, 'four': 4}
print("Before sort")
print(data)
orderd_dict = collections.OrderedDict(sorted(data.items()))
print("After sort")
print(orderd_dict)
Output:
Before sort
{'one': 1, 'three': 3, 'two': 2, 'four': 4}
After sort
OrderedDict([('four', 4), ('one', 1), ('three', 3), ('two', 2)])
Order dict key by its length:
Do you want to order the keys based on its length? yes, it can be possible by providing key as a parameter.
import collections
if __name__ == '__main__':
data = {'one': 1, 'three': 3, 'two': 2, 'four': 4}
print("Before sort")
print(data)
orderd_dict = collections.OrderedDict(sorted(data.items(), key=lambda t: len(t[0])))
print("After sorting by key length")
print(orderd_dict)
Output:
Before sort
{'one': 1, 'three': 3, 'two': 3, 'four': 4}
After sorting by key length
OrderedDict([('one', 1), ('two', 2), ('four', 4), ('three', 3)])
References:
Happy Learning 🙂