
Dictionary is a popular and relatively widely used data type in Python programming language. This type of data is basically an associative list or key-value list. In this post, I'll talk comprehensively about dictionary in Python.
We usually use the Python dictionary in places where we need to identify values using a key associated with each of them. These values can be anything; For example, text string, number, object, etc.
At first, I'll discuss what a dictionary is in Python, and then I'll explain how to create a dictionary and work with a Python dictionary. Also, at the end, I'll talk more about the types of keys and values and review some practical tricks together.
In a dictionary book, a word is associated with its equivalent. This equivalent can be one or several, but the main word is one! Basically, we have linked one or more equivalent meanings to a word.
We do exactly the same thing in the Python dictionary; A word (which we know as a key) will be associated with a value (string, number, object reference, etc.).
Usually, the elements of a dictionary are related items and each element expresses a feature or characteristic of the main item. But this issue will depend entirely on your definitions and programming type as a programmer, and we don't have any special rules about the relevance of the elements of a dictionary!
Creating a dictionary in Python
A dictionary starts with {
and ends with }
. Key dictionary elements are defined as key and value (key-value) inside it and similar to other common storage structures in Python, they are separated from each other by using comma (,
).
For example, suppose we want to have the specifications of our desired account in the hive in a dictionary; We define the dictionary as follows.
person = {
"username": "albro",
"job": "programmer",
"home": "Hive Blockchain",
"age": 27
}
In this simple way, we were able to create a dictionary containing individual information called albro!
The number of elements in a Python dictionary is unlimited. We can have a dictionary with thousands of elements or just store one element inside it. Only the key and value definition rules should be observed for them.
Create a dictionary with the dict
constructor
You can also use its constructor to create a dictionary. For this purpose, we call the dict()
function and give all the keys and their values as separate parameters as input to the function.
person = dict( username="albro", job="programmer", home="Hive Blockchain", age=27 )
The result stored in the person
variable is also similar to the previous case. In fact, there is no special difference in the dictionary created in these two modes. You can use them in whatever way is most convenient for you.
Of course, as you know, sometimes the conditions of the program and upcoming situations determine how to use it for us.
Working with dictionaries in Python
So far, we were able to create a dictionary in Python. It is definitely necessary to be able to perform operations with the elements in it to advance our program. In the following, we read the methods of working with dictionary elements.
Accessing dictionary values
There are two ways to access the values (elements) stored in the dictionary.
The first and simplest solution is similar to accessing the houses of a list in Python. in such a way that by using the sign []
, you can access each element; with the difference that instead of a numerical value for the index, we will use the value of the keys as an index.
If we want to access a person's username
in the dictionary we created at the beginning of the work, we will proceed as follows.
print( "Username: " + person["username"] )
The output of the above code will be something like the following:
Username: albro
The second solution to access the value of a key in the Python dictionary is to use the get()
function on the dictionary. This function takes an input that is the key we want and then returns the value associated with the key.
print( "Username: " + person.get("username") )
# output: Username: albro
KeyError
error in Python dictionary
If we call a key that does not exist while calling a value from the dictionary, we will encounter a KeyError
type error.
info = {'name': 'albro', 'job': 'programmer', 'code': 177}
print( info['name'] )
print( info['family'] )
# albro
# KeyError: 'family'
Change dictionary values in Python
To update the value of each key, we act similar to assigning the value to different indexes of a list.
In the following code, we have put the value 23 in the age
key of the person
dictionary.
person["age"] = 23
As you've probably guessed, updating the value of a key in a dictionary can also be done using the same value or other values in that dictionary.
For example, in the following example, we increase the current age of the user by one unit.
person["age"] = person["age"] + 1

Adding a new element to a Python dictionary
Adding a new element to a dictionary in Python is very easy and simple. For this, we act similar to changing the value of a key in the dictionary, with the difference that the called key is the new key and the value assigned to it will be the desired value.
person["mobile"] = "Samsung Galaxy Note 7"
Remove elements from the dictionary
To delete a key and its associated value, we will have two methods.
The first method is to use the del
statement. In front of this statement, we call the desired key in the dictionary.
print( person )
del person["mobile"] # delete 'mobile' key in dictionary
print( person )
In the output of the code above, in the second print, we see that the mobile
key and its corresponding value have been removed from the dictionary.
{'username': 'albro', 'job': 'programmer', 'home': 'Hive Blockchain', 'age': 27, 'mobile': 'Samsung Galaxy Note 7'}
{'username': 'albro', 'job': 'programmer', 'home': 'Hive Blockchain', 'age': 27}
The second method to remove an element from the dictionary is to use the pop()
method in the Python dictionary. This function is called as a method on the desired dictionary and takes an entry.
Its entry is the value of the desired key that we want to remove from the dictionary.
person.pop("age")
Delete the entire dictionary in Python
Sometimes it is necessary to delete the entire dictionary. The whole dictionary means removing all the keys and values and then removing the dictionary variable.
For this, it is enough to write the name of the dictionary in front of the del
statement. This will delete the entire dictionary.
del person # delete person dictionary object
Remove all dictionary elements
But sometimes it is necessary to simply empty the dictionary; That is, without deleting the dictionary itself, just delete the keys and values. For this, we call the clear()
method on the dictionary object.
By calling this function, all the keys in the dictionary will be deleted, and finally we will have an empty dictionary.
person.clear() # delete all keys in Dictionary
print( person )
# output: {}
Key and value definition rules in Python dictionary
Dictionary keys in Python should have two main features.
- be unique (not duplicate)
- be immutable.
The first one is almost obvious. In fact, there cannot be more than one value for each key in the dictionary. If a key is defined twice in the dictionary, the second value will replace the first one and we will always have the second value. (somehow the value changes)
In the case of the second rule, the key is considered to be the identity of the value associated with it. We know that identity cannot be changed. Therefore, the keys in the Python dictionary must be an immutable value. As a result, a variable cannot be used as a key.
We do not have any restrictions for the values corresponding to the keys in the dictionary. These values can be repeated or any different data type (such as Python text string, number, Python object, user-defined object, etc.); As a result, they can also be changeable.
Copying a dictionary in Python
As you know, variables that point to objects contain a reference to that object. So if we assign a dictionary to another variable using the assignment sign (=
), the dictionary will not be copied; Rather, only its reference will be thrown into the second variable. As a result, by changing the first dictionary, our second dictionary will also change.
person_backup = person # not a true way to copy dictionary
To copy a dictionary in Python, you can use the copy()
method on the dictionary object.
person_backup = person.copy()
Now, if we change the dictionary person
or person_backup
, the contents of the dictionary will not change.
Summary: Dictionary in Python
A dictionary in Python is an associative or key-value list. If you are familiar with lists in Python, you know that we use indices to access each element in the list. In the index dictionary (or key) we will define each value by ourselves.
In this post, I discussed how to make a dictionary in Python, different rules and methods of working with it. We have seen that dictionaries can be easily used. Dictionaries are one of the most popular and widely used data structures in Python that can be used in various parts of your program.
What tricks do you think are useful in working with the Python dictionary that have not been mentioned? Share this trick with your friends in the comments section. If you have any questions, the comments section is for you!