Methods of Ordered Dictionary in Python
Last Updated :
16 Feb, 2022
An OrderedDict is a dict that remembers the order in that keys were first inserted. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end. Ordered dictionary somehow can be used in the place where there is a use of hash Map and queue. It has characteristics of both into one. Like queue, it remembers the order and it also allows insertion and deletion at both ends. And like a dictionary, it also behaves like a hash map.
Note: From Python 3.6 onwards, the order is retained for keyword arguments passed to the OrderedDict constructor, refer to PEP-468.
Methods of ordered Dictionary
Let’s look at various methods offered by the ordered dictionary.
This method is used to delete a key from the beginning.
Syntax:
popitem(last = True)
If the last is False then this method would delete a key from the beginning of the dictionary. This serves as FIFO(First In First Out) in the queue otherwise it method would delete the key from the end of the dictionary.
Time Complexity: O(1).
For Better Understanding have a look at the code.
Python3
from collections import OrderedDict
ord_dict = OrderedDict().fromkeys( 'GeeksForGeeks' )
print ( "Original Dictionary" )
print (ord_dict)
ord_dict.popitem()
print ( "\nAfter Deleting Last item :" )
print (ord_dict)
ord_dict.popitem(last = False )
print ( "\nAfter Deleting Key from Beginning :" )
print (ord_dict)
|
Output:
Original Dictionary
OrderedDict([(‘G’, None), (‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None)])
After Deleting Last item :
OrderedDict([(‘G’, None), (‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None)])
After Deleting Key from Beginning :
OrderedDict([(‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None)])
This method is used to move an existing key of the dictionary either to the end or to the beginning. There are two versions of this function –
Syntax:
move_to_end(key, last = True)
If the last is True then this method would move an existing key of the dictionary in the end otherwise it would move an existing key of the dictionary in the beginning. If the key is moved at the beginning then it serves as FIFO ( First In First Out ) in a queue.
Time Complexity: O(1)
Python3
from collections import OrderedDict
ord_dict = OrderedDict().fromkeys( 'GeeksForGeeks' )
print ( "Original Dictionary" )
print (ord_dict)
ord_dict.move_to_end( 'G' )
print ( "\nAfter moving key 'G' to end of dictionary :" )
print (ord_dict)
ord_dict.move_to_end( 'k' , last = False )
print ( "\nAfter moving Key in the Beginning :" )
print (ord_dict)
|
Output:
Original Dictionary
OrderedDict([(‘G’, None), (‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None)])
After moving key ‘G’ to end of dictionary :
OrderedDict([(‘e’, None), (‘k’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None), (‘G’, None)])
After moving Key in the Beginning :
OrderedDict([(‘k’, None), (‘e’, None), (‘s’, None), (‘F’, None), (‘o’, None), (‘r’, None), (‘G’, None)])
Working of move_to_end() function
Basically, this method looks up a link in a linked list in a dictionary self.__map and updates the previous and next pointers for the link and its neighbors. It deletes that element from its position and adds it to the end or beginning depending upon parameter value. Since all of the operations below take constant time, the complexity of OrderedDict.move_to_end() is constant as well.
Similar Reads
Python Dictionary Methods
Python dictionary methods is collection of Python functions that operates on Dictionary. Python Dictionary is like a map that is used to store data in the form of a key: value pair. Python provides various built-in functions to deal with dictionaries. In this article, we will see a list of all the f
5 min read
Are Python Dictionaries Ordered?
Yes, as of Python 3.7, dictionaries are ordered. This means that when you iterate over a dictionary, insert items, or view the contents of a dictionary, the elements will be returned in the order in which they were added. This behavior was initially an implementation detail in Python 3.6 (in the CPy
3 min read
Python Dictionary items() method
items() method in Python returns a view object that contains all the key-value pairs in a dictionary as tuples. This view object updates dynamically if the dictionary is modified. Example: [GFGTABS] Python d = {'A': 'Python', 'B': 'Java', 'C': 'C++'} #
2 min read
Iterate over a dictionary in Python
In this article, we will cover How to Iterate Through a Dictionary in Python. To Loop through values in a dictionary you can use built-in methods like values(), items() or even directly iterate over the dictionary to access values with keys. How to Loop Through a Dictionary in PythonThere are multip
6 min read
Python Dictionary fromkeys() Method
Python dictionary fromkeys() function returns the dictionary with key mapped and specific value. It creates a new dictionary from the given sequence with the specific value. Python Dictionary fromkeys() Method Syntax: Syntax : fromkeys(seq, val) Parameters : seq : The sequence to be transformed into
3 min read
Python Dictionary Exercise
Basic Dictionary ProgramsPython | Sort Python Dictionaries by Key or ValueHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPython program to find the sum of all items in a dictionaryPython program to find the size of a DictionaryWays to sort list of dicti
3 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value ca
5 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read
Update Nested Dictionary - Python
A nested dictionary in Python is a dictionary that contains another dictionary (or dictionaries) as its value. Updating a nested dictionary involves modifying its structure or content by: Adding new key-value pairs to any level of the nested structure.Modifying existing values associated with specif
4 min read
Get Key from Value in Dictionary - Python
The goal is to find the keys that correspond to a particular value. Since dictionaries quickly retrieve values based on keys, there isn't a direct way to look up a key from a value. Using next() with a Generator ExpressionThis is the most efficient when we only need the first matching key. This meth
6 min read