Dictionaries in Python
In this entry, we will talk about such a data type as a dictionary. What it is? A dictionary is a data structure in which information is stored in a key-value format. Here I will explain how to access the information stored in a dictionary and how to edit this information, talk about the main methods of dictionaries and how to use them.
Let's create 2 dictionaries, one stores information about students' grades, the other contains a list of students who eat in the canteen (Fig. 1.1). The dictionary is written in curly brackets. It can either contain initial data (students_marks) or be empty (student_who_eat_in_dining_room).
As mentioned earlier, all information in dictionaries is stored in the key-value format. If we need to get the value assigned to a particular key, we can do it directly or through the get() method. If the key we entered is missing, then the get() method will return None, but the call without it will give an error. This is important to consider when creating projects where it is not known for sure whether a key with the same name exists in the dictionary.
We can also add new keys and values, as well as change the values already in the dictionary. All the actions described above and their result can be seen in Fig. 1.1-1.2.
Figure. 1.1. Program listing 1
Figure. 1.2. Program output 1
Consider two other methods, namely keys() and values(). The first returns us all the keys in the dictionary, the second returns all the values, such as dict_keys and dict_values respectively. If we need to remove a pair from a dictionary, we can use del or pop (). To display all key-value pairs, you need the items() method.
Figure. 2.1. Program listing 2
Figure. 2.2. Program output 2
To view these and other Python programs, you can visit my repository.