Regular Dictionary vs Ordered Dictionary in Python
Last Updated : 05 Sep, 2024
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 does not track the insertion order of the (key, value) pairs and thus iterates through the keys based on how they are stored in the hash table which in turn is based on random values to reduce collisions .In contrast to this Python provides the OrderedDict type which remembers the insertion order of (key, value) pairs in the dictionary and thus preserves the order. OrderedDict consumes more memory than a regular dictionary in Python because of the underlying Doubly LinkedList implementation to preserve the order.
Note : A regular dictionary maintains the insertion order from Python 3.7 onwards.
Regular Dictionary vs Ordered Dictionary in Python
There are differences between a Regular Dictionary and an Ordered Dictionary in Python, here we are discussing differences between some characteristics of a Regular Dictionary and vs Ordered Dictionary.
- Create and Print Dictionary
- Dictionary Deletion and Re-insertion
- Ordering of Elements
- Equality Comparison
Create and Print Dictionary
In a regular dictionary, the order of key-value pairs is not guaranteed, so the output may vary when printing. In contrast, an ordered dictionary maintains the order of insertion, ensuring that elements are printed in the sequence they were added
In this example, code illustrates the distinction between a regular dictionary and an ordered dictionary in Python. It creates a regular dictionary with arbitrary order and prints its content, then generates an ordered dictionary using `collections.OrderedDict()`.
Python import collections # Creating a regular dictionary print('Regular dictionary:') d = {chr(k): k for k in range(ord('a'), ord('g'))} for k, v in d.items(): print(k, v) # Creating an Ordered dictionary print('\nOrderedDict:') d = collections.OrderedDict() [d.setdefault(chr(k), k) for k in range(ord('a'), ord('g'))] for k, v in d.items(): print(k, v)
Output (Python 3.6 and earlier)::
Regular dictionary:
('a', 97)
('c', 99)
('b', 98)
('e', 101)
('d', 100)
('f', 102)
OrderedDict:
('a', 97)
('b', 98)
('c', 99)
('d', 100)
('e', 101)
('f', 102)
Time complexity : O(N)
Space Complexity : O(N)
Note: Starting from Python 3.7, insertion order of Python dictionaries is guaranteed.
Dictionary Deletion and Re-insertion
Deleting and re-inserting the same key will push it to the back as OrderedDict however maintains the order of insertion. In a regular dictionary, deletion and re-insertion of a key-value pair do not guarantee a specific order upon iteration. However, in an ordered dictionary, the order of insertion is preserved, so deleting and re-inserting a key-value pair maintains its position in the iteration sequence
In this example Python code demonstrates the use of deletion and re-insertion operations in both a regular dictionary (dict
) and an ordered dictionary (OrderedDict
).
Python from collections import OrderedDict print("Before deleting:\n") d = {} print("Regular dictionary:") d['a'] = 1 d['b'] = 2 d['c'] = 3 d['d'] = 4 for key, value in d.items(): print(key, value) od = OrderedDict() print("\nOrdered dictionary:") od['a'] = 1 od['b'] = 2 od['c'] = 3 od['d'] = 4 for key, value in od.items(): print(key, value) print("\nAfter deleting:\n") print("Regular dictionary:") d.pop('c') for key, value in d.items(): print(key, value) print("\nOrdered dictionary:") od.pop('c') for key, value in od.items(): print(key, value) print("\nAfter re-inserting:\n") print("Regular dictionary:") d['c'] = 3 for key, value in d.items(): print(key, value) print("\nOrdered dictionary:") od['c'] = 3 for key, value in od.items(): print(key, value)
Output (Python 3.6 and earlier):
Before deleting:
Regular dictionary:
('a', 1)
('c', 3)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('c', 3)
('d', 4)
After deleting:
Regular dictionary:
('a', 1)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('d', 4)
After re-inserting:
Regular dictionary:
('a', 1)
('c', 3)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('d', 4)
('c', 3)
Time Complexity : O(n)
Space Complexity :O(1)
Ordering of Elements
In a regular dictionary, the order of elements is not guaranteed, and iterating over its items may not reflect the order of insertion. Conversely, an ordered dictionary, specifically OrderedDict
in Python, ensures that the order of elements remains consistent with the sequence of their insertion, providing a reliable and predictable iteration order
In this example code first demonstrates a regular dictionary’s unpredictable order when iterated, printing key-value pairs. Then, it contrasts this with an ordered dictionary, showcasing its guaranteed order of insertion by printing its key-value pairs in the order they were added.
Python print("Regular Dictionary is :") regular_dict = {'one': 1, 'three': 3, 'two': 2} for key, value in regular_dict.items(): print(key, value) from collections import OrderedDict print("Ordered Dictionary is :") ordered_dict = OrderedDict([('one', 1), ('three', 3), ('two', 2)]) for key, value in ordered_dict.items(): print(key, value)
Output :
Regular Dictionary is :
one 1
three 3
two 2
Ordered Dictionary is :
one 1
three 3
two 2
Time Complexity: O(N)
Space Complexity: O(1)
Equality Comparison
Regular dictionaries in Python do not guarantee any specific order of key-value pairs, so their equality comparison checks if the contents are the same, regardless of order. On the other hand, ordered dictionaries preserve the order in which items are inserted, so their equality comparison considers both content and order for equality.
In this example first part uses regular dictionaries (dict1 and dict2) with different key orders, yielding True in the equality check (dict1 == dict2) because regular dictionaries ignore order. The second part involves ordered dictionaries (od1 and od2) with the same content but different key orders, resulting in False in the equality check (od1 == od2) as ordered dictionaries consider both content and order.
Python print("Regular Dictionary Equality Comparison : ") dict1 = {'one': 1, 'two': 2, 'three': 3} dict2 = {'three': 3, 'two': 2, 'one': 1} print(dict1 == dict2) from collections import OrderedDict print("Ordered Dictionary Equality Comparison : ") od1 = OrderedDict([('one', 1), ('two', 2), ('three', 3)]) od2 = OrderedDict([('three', 3), ('two', 2), ('one', 1)]) print(od1 == od2)
Output :
Regular Dictionary Equality Comparison :
True
Ordered Dictionary Equality Comparison :
False
Similar Reads
Update Dictionary with other Dictionary - Python
The task of updating a dictionary with another dictionary involves merging the key-value pairs from one dictionary into another. If a key already exists in the target dictionary, its value is updated with the value from the source dictionary. If the key does not exist in the target dictionary, it is
4 min read
Append Dictionary Keys and Values ( In order ) in Dictionary - Python
Appending dictionary keys and values in order ensures that the sequence in which they are added is preserved. For example, when working with separate lists of keys and values, we might want to append them in a specific order to build a coherent dictionary. Let's explore several methods to achieve th
3 min read
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 - Custom order dictionary
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 dic
3 min read
Python - Filter dictionary values in heterogeneous dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to filter out certain values based on certain conditions on a particular type, e.g all values smaller than K. This task becomes complex when dictionary values can be heterogeneous. This kind of problem can have
6 min read
Sort a Nested Dictionary by Value in Python
Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of
3 min read
Python | Max/Min of tuple dictionary values
Sometimes, while working with data, we can have a problem in which we need to find the min/max of tuple elements that are received as values of dictionary. We may have a problem to get index wise min/max. Let's discuss certain ways in which this particular problem can be solved. Method #1 : Using tu
5 min read
Python - Remove duplicate values in dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the removal of all the duplicate values of dictionary, and we are not concerned if any key get removed in the process. This kind of application can occur in school programming and day-day programming.
8 min read
Python - Sorted Nested Keys in Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be perf
4 min read
Python - Filter dictionaries with ordered values
Given the dictionary list, the task is to write a python program to filter dictionaries with values in increasing order i.e sorted. Examples: Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : 4}] Output : [{'gfg': 2, 'is': 8, 'good':
4 min read