In Python, a dictionary is an unordered sequence of data entries that can be used to record data entries in the same way that a map can. Unlike alternative data structures that only carry a singular item as an object, Dictionary contains a key: value pair. The dictionary includes a Key-Value field to improve the efficiency of this data type.
Creating a Dictionary
We can create a dictionary in Python by wrapping a collection of objects in curly brackets and segregating them with a comma. The Dictionary keeps track of a couple of entries, one part of this is called a key, and the other is called the value of the key and is referred to as the key: value pair. We can store any data type as a value for the key and give the same value to two keys, but keys should be immutable and unique.
Code
Output:
The built-in method dict() could also be used to generate a dictionary. By simply placing two curly brackets {}, a blank dictionary can be built.
Code
Output:
Adding Elements to a Dictionary
The insertion of items in the Python Dictionary could be done in various methods. Items can be added to the dictionary using this particular format Dictionary[Key] = 'Value'. We can use the in-built update() function to update a current key in a Dictionary. Nested key: values can also be inserted into a preexisting Dictionary. If the key-value combination is present in the dictionary, the value for that key is modified; if this is not the case, a new key is created and added to the Dictionary with the given value.
Code
Output:
Removing Elements from Dictionary
Using the pop() function, we can eliminate a specific item from a dictionary. This function returns the value of the key removed.
The popitem() function removes and returns any (key, value) element pair from the given dictionary. We can use the clear() function to erase all objects in one go.
We could also use the del keyword to eliminate single items or even the entire dictionary.
Code
Output:
Python Dictionary Methods
The techniques that we can use with a dictionary are listed below. Some of these have already been mentioned in this tutorial.