A dictionary is a set of unordered key, value pairs. In a dictionary, the keys must be unique and they are stored in an unordered manner.
In this tutorial you will learn the basics of how to use the Python dictionary.
Creating a Dictionary:
You can access the items of a dictionary by referring to its key name, inside square brackets:
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example −
Loop Through a Dictionary:
You can loop through a dictionary by using a for loop.When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
Check if Exists:
You can test the presence of a key using ‘in’ or ‘not in’
Restrictions on Dictionary Keys:
Almost any type of value can be used as a dictionary key in Python. As an example, integer, float, and Boolean objects are used as keys:
However, there are a couple restrictions that dictionary keys must abide by.
First, a given key can appear in a dictionary only once. Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn’t make sense to map a particular key more than once.
You could see below that when you assign a value to an already existing dictionary key, it does not add the key a second time, but replaces the existing value:
Restrictions on Dictionary Values:
By contrast, there are no restrictions on dictionary values. Literally none at all. A dictionary value can be any type of object Python supports, including mutable types like lists and dictionaries, and user-defined objects.There is also no restriction against a particular value appearing in a dictionary multiple times.
Hope you have enjoyed the post. Keep reading