Python - Custom order dictionary
Last Updated :
29 Mar, 2023
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the custom ordering of keys of dictionary. This is quite popular problem, with the advent of newer version of Python, where keys are ordered in Dictionaries, there might be requirement to reorder dictionary keys. Let's discuss certain ways in which this task can be performed.
Input : test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'geeks': 5} Output : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'geeks': 5} Input : test_dict = {'geeks': 5, 'for': 4, 'best': 3, 'is': 2, 'gfg': 1} Output : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'geeks': 5}
Method #1 : Using loop This is brute force way to solve this problem. In this, we construct the newer dictionary by appending the keys in order list, mapping with keys in original dictionary. Works with Python >= 3.6.
Python3
# Python3 code to demonstrate working of
# Custom order dictionary
# Using loop
# initializing dictionary
test_dict = {'is' : 2, 'for' : 4, 'gfg' : 1, 'best' : 3, 'geeks' : 5}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing order
ord_list = ['gfg', 'is', 'best', 'for', 'geeks']
# Custom order dictionary
# Using loop
res = dict()
for key in ord_list:
res[key] = test_dict[key]
# printing result
print("Ordered dictionary is : " + str(res))
Output :
The original dictionary is : {'is': 2, 'for': 4, 'gfg': 1, 'best': 3, 'geeks': 5} Ordered dictionary is : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'geeks': 5}
Method #2 : Using dictionary comprehension This is yet another way in which this task can be performed. In this, we use shorthand to solve the problem using the same above method.
Python3
# Python3 code to demonstrate working of
# Custom order dictionary
# Using dictionary comprehension
# initializing dictionary
test_dict = {'is' : 2, 'for' : 4, 'gfg' : 1, 'best' : 3, 'geeks' : 5}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing order
ord_list = ['gfg', 'is', 'best', 'for', 'geeks']
# Custom order dictionary
# Using dictionary comprehension
res = {key : test_dict[key] for key in ord_list}
# printing result
print("Ordered dictionary is : " + str(res))
Output :
The original dictionary is : {'is': 2, 'for': 4, 'gfg': 1, 'best': 3, 'geeks': 5} Ordered dictionary is : {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'geeks': 5}
Using a list comprehension and the min function:
Approach:
We can use a list comprehension to generate a list of tuples containing the key-value pairs, find the minimum key using the min function, and then create a new dictionary by iterating over the keys in sorted order.
Python3
def order_dict_4(input_dict):
pairs = [(k, v) for k, v in input_dict.items()]
min_key = min(pairs, key=lambda x: x[0])[0]
return {k: v for k, v in sorted(pairs, key=lambda x: x[0]-min_key)}
test_dict = {'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'geeks': 5}
print(test_dict)
test_dict = {'geeks': 5, 'for': 4, 'best': 3, 'is': 2, 'gfg': 1}
print(test_dict)
Output{'gfg': 1, 'is': 2, 'best': 3, 'for': 4, 'geeks': 5}
{'geeks': 5, 'for': 4, 'best': 3, 'is': 2, 'gfg': 1}
Time complexity: O(n log n), where n is the number of key-value pairs in input_dict. This is because we need to sort the list of tuples using sorted.
Auxiliary Space: O(n), as a new list and dictionary need to be created to store the sorted key-value pairs.
Similar Reads
Reverse Dictionary Keys Order - Python We are given a dictionary and our task is to reverse the order of its keys. This means if we have a dictionary like {'a': 1, 'b': 2, 'c': 3} then the output will be {'c': 3, 'b': 2, 'a': 1}. This can be done using methods like reversed(), dictionary comprehensions, or OrderedDict. Let's explore thes
4 min read
Python - Combine dictionary with priority Sometimes, while working with dictionary data, we can have problem in which we need to combine two dictionaries. This is very common problem. But a variation of this can be combining dictionaries, and giving precedence to a particular dictionary if both the keys clash in dictionaries. Let's discuss
3 min read
Regular Dictionary vs Ordered Dictionary in Python Dictionary in Python is an unordered collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, a Dictionary holds key: value pair. Key-value is provided in the dictionary to make it more optimized. A regular dictionary type
5 min read
Python - Custom dictionary initialization in list While working with Python, we can have a problem in which we need to initialize a list of a particular size with custom dictionaries. This task has itâs utility in web development to store records. Letâs discuss certain ways in which this task can be performed. Method #1 : Using {dict} + "*" operato
3 min read
Sort a Dictionary - Python In Python, dictionaries store key-value pairs and are great for organizing data. While they werenât ordered before Python 3.7, you can still sort them easily by keys or values, in ascending or descending order. Whether youâre arranging names alphabetically or sorting scores from highest to lowest, P
5 min read