
Course with employment: “Profession Python Developer"
Learn MoreA dictionary in Python is a collection of key: value pairs. Key features of a dictionary include the ability to store unordered data, access values by unique keys, and dynamic resizing. Dictionaries are useful tools for organizing and managing data, allowing you to efficiently search, add, and delete items. Due to their flexibility and ease of use, dictionaries are widely used in a variety of Python programming tasks, from simple to complex.
- In each pair, a key points to a value.
- Keys are unique, there are no duplicates. Values can be the same.
- Unlike a list or tuple, a dictionary is unordered, meaning you can't specify which pair comes first or last.
Keys and values in a dictionary are separated by colons, with key-value pairs separated by commas. The entire dictionary must be enclosed in curly braces {}. This format allows for easy structuring of data and ensures its convenient use in programming and web development. Proper dictionary formatting promotes better understanding of the information and facilitates its processing.
Keys in Python can be strings, integers, floats, and tuples. However, lists, dictionaries, and other mutable data types cannot be used as keys. Values can be any data type, allowing for the creation of flexible and powerful data structures.
Working with a dictionary involves retrieving values by a given key. Several methods allow for this process to be accomplished efficiently. By using different approaches, you can optimize interaction with dictionaries and improve the performance of your code.

The usual (not so good) way
Beginning Python programmers often learn the first way to extract values from a dictionary using square brackets. This requires specifying the dictionary name followed by the key in square brackets. If Python finds the specified key in the dictionary, it returns the corresponding value. This method is the primary way to work with dictionaries in Python and allows for efficient data retrieval.
If there is no such key, a KeyError exception will be returned. And this, it must be said, is quite unpleasant, especially in the case of large and frequently changing data.
There are several ways to solve this problem.
- Use the try / except construct (similar to the if / else conditional statement), which will handle the KeyError and return not the exception itself, but something more convenient for work, for example, a message.
- Use the built-in collections library, and specifically the defaultdict structure from it - an extension on a regular dictionary that allows you to set default values for requested non-existent keys.
A Python dictionary offers two useful built-in methods for working with values: .get() and .setdefault(). These methods allow you to avoid exception handling and do not require importing additional libraries. Let's take a closer look at their functionality and usage. The .get() method returns the value for the specified key. If the key is missing, it doesn't raise an error but returns the default value. The .setdefault() method also returns the value for the key, but if the key is missing, it adds it to the dictionary with the specified value. Using these methods simplifies working with dictionaries and makes code cleaner and more understandable.
Calling with .get()
The most reliable method of retrieving values from a dictionary involves using two parameters. This approach provides the greatest safety when working with data, allowing you to avoid errors and exceptions. Proper use of these parameters ensures that you get the desired value, even if the key is not in the dictionary. This approach is especially relevant for developers striving to create stable and resilient applications.
- The first (required) is the key whose value we want to retrieve.
- The second (optional) is the value that the method will return if the key does not exist in the dictionary. By default, it is None, which is what the method will return.
If the key is in the dictionary, calling the .get() method is equivalent to calling it using square brackets. However, if the key is not present, the .get() method returns the value of the second parameter, which can be None or, for example, a text message. This approach avoids errors associated with accessing a non-existent key, making .get() safer and more convenient for working with dictionaries in Python.
Calling with .setdefault()
Sometimes you may need not only protection against the KeyError error, but also fix the dictionary itself. For this, the .setdefault() method is used, which is similar in syntax and output to .get() and takes the same two parameters: the key being called and its default value.
The .setdefault() method is used in Python to work with dictionaries. When you call .setdefault() with a specific key, it checks if the key exists in the dictionary. If the key is present, the method returns its value. If the key is not present, the method adds it to the dictionary with the specified default value and returns this value. This avoids errors associated with the absence of a key and conveniently initializes values in a dictionary. Use .setdefault() to efficiently manage dictionary data and simplify your code.
- creates the key itself;
- pairs it with the value you specify (None by default);
- adds the resulting pair to the dictionary;
- returns the value.
If you do not specify the second parameter, the function will return None, which means no result. This is important to keep in mind when working with functions to avoid errors and properly handle return values.
It is important to note that this method does not change the values of existing keys.
So, in summary
If you do not plan to modify the contents of the dictionary, it is recommended to use the .get() method, which allows you to safely retrieve values by keys. If you need to add missing keys and values to the dictionary, the .setdefault() method is the optimal solution. Both of these methods provide greater reliability than traditional square bracket notation, avoiding errors related to missing keys.
If you want to deepen your knowledge, enroll in the "Becoming a Python Developer" course. We'll teach you all the essential Python methods and tools to help you successfully find a job in programming. Join us and start your career as a Python developer!

