Introduction to Dictionaries in Python
Hi everyone, in this article, we will talk about Python dictionaries. This is the third article in a row where we talk about built-in data types in Python. You can read about Python lists and Python tuples.
Description
A dictionary is used to store data in the form of key: value pairs. The elements of a dictionary are ordered (from Python version 3.7), so the items have a defined order, that will not change.
Moreover, dictionaries in Python are changeable, which means that we can add, update or delete items after the creation of a dictionary. Be careful that the values of a dictionary are mutable, not the keys. If we try to change the value of a key we will get an error.
Another feature of dictionaries is that they don’t allow duplicate values, so we cannot have more than one element with the same key. From the Python perspective, a dictionary is defined as an object of class dict. You can check it using the function type().
Create a Dictionary
We can create a dictionary with various ways, but the most common of them is by using curly brackets having keys and values separated by commas, as follows:
my_dict = {
"key1" : value1,
"key2: : value2,
...
"keyn" : valuen
}