Working with Dictionaries in Python: Efficient Adding, Searching, and Deleting Data
Dictionaries (dict) in Python are a fundamental data structure that plays a crucial role in development. They allow you to efficiently organize and manage data in a "key-value" format. Mastering working with dictionaries is essential for every Python developer, as they are used in a wide range of tasks, from storing configuration settings to implementing complex algorithms.
In this guide, we will thoroughly examine the basic operations with dictionaries in Python: creating, adding, deleting, and searching data. The code examples provided will help you reinforce your knowledge in practice and confidently use dictionaries in your projects.
What is a Dictionary (dict) in Python?
A dictionary (dict) is a mutable collection that represents a set of "key-value" pairs. Keys in a dictionary must be unique and belong to immutable data types (strings, numbers, tuples), while values can be any Python objects. Dictionaries provide fast access to data by key, making them ideal for tasks requiring efficient searching and storing of information.
Example of a dictionary:
person = {
"name": "Ivan",
"age": 30,
"city": "Moscow"
}
Creating a Dictionary in Python
There are several ways to create dictionaries in Python:
-
Using curly braces
{}:user = {"username": "admin", "password": "1234"} -
Using the
dict()function:config = dict(debug=True, version="1.0") -
Using the
zip()function to combine keys and values:keys = ["name", "age"] values = ["Anna", 25] user_info = dict(zip(keys, values))
Adding Data to a Dictionary
You can add new elements to a Python dictionary in several ways:
-
Adding a new "key-value" pair directly:
user = {"name": "Alexey"} user["age"] = 28 print(user) # {'name': 'Alexey', 'age': 28} -
Using the
update()method:user.update({"city": "Saint Petersburg"})
The update() method allows you to add multiple elements at once. If a key already exists, its value will be updated.
Accessing a Dictionary by Key
To access a value in a dictionary by key, you can use:
-
Square brackets
[]:person = {"name": "Maria", "age": 22} print(person["name"]) # Output: Maria
It is important to remember that if the key does not exist, a KeyError will occur.
-
The
get()method for safe access:print(person.get("city", "City not specified")) # Output: City not specified
The get() method returns the value for the key, and if the key is missing, it returns a default value (in this case, "City not specified").
Checking for the Existence of a Key in a Dictionary
You can check if a key exists in a dictionary using the in operator:
person = {"name": "Maria", "age": 22}
if "age" in person:
print("Age is specified.")
else:
print("Age is not specified.")
Deleting Data from a Dictionary
The following methods are used to delete elements from a Python dictionary:
-
The
deloperator:user = {"name": "Irina", "age": 29} del user["age"] print(user) # {'name': 'Irina'} -
The
pop()method:user = {"name": "Irina", "age": 29} removed_value = user.pop("name") print(removed_value) # Irina print(user) # {'age': 29}
The pop() method removes the element by key and returns its value. If the key is not found, you can specify a default value that will be returned:
user = {"name": "Irina", "age": 29}
user.pop("city", "City not found") # Will not cause an error even if the "city" key does not exist
-
The
clear()method: completely clearing the dictionary:user = {"name": "Irina", "age": 29} user.clear() print(user) # {}
Iterating Through a Dictionary
The following methods are used to iterate through the elements of a dictionary:
-
Iterating through keys only:
person = {"name": "Maria", "age": 22} for key in person.keys(): print(key) -
Iterating through values only:
person = {"name": "Maria", "age": 22} for value in person.values(): print(value) -
Iterating through "key-value" pairs:
person = {"name": "Maria", "age": 22} for key, value in person.items(): print(f"{key}: {value}")
Combining Dictionaries
There are several ways to combine two dictionaries in Python:
-
The
|operator (starting with Python 3.9):dict1 = {"a": 1} dict2 = {"b": 2} merged = dict1 | dict2 print(merged) # {'a': 1, 'b': 2} -
The
update()method:dict1 = {"a": 1} dict2 = {"b": 2} dict1.update(dict2) print(dict1) # {'a': 1, 'b': 2}
When using update(), the dictionary to which the method is applied is modified.
Advanced Dictionary Operations
Dictionaries with Nested Structures
Dictionaries can contain nested structures, such as other dictionaries or lists. This allows you to create complex hierarchical data structures.
employees = {
"e1": {"name": "Olga", "position": "Manager"},
"e2": {"name": "Dmitry", "position": "Developer"}
}
Access to nested data is done by sequentially specifying keys:
print(employees["e1"]["position"]) # Manager
Using Dictionaries as an Alternative to Switch/Case
Python does not have a switch/case statement, as in some other programming languages. However, dictionaries can be used to implement similar functionality.
def monday():
return "Monday"
def tuesday():
return "Tuesday"
days = {
1: monday,
2: tuesday
}
print(days[1]()) # Monday
In this example, the days dictionary associates numeric keys with functions that return the names of the days of the week.
FAQ – Frequently Asked Questions
-
What to do if an error occurs when accessing a key?
Use the
.get()method for safe access and to provide a default value. -
Can a list be used as a key in a dictionary?
No. The key must be an immutable data type, such as a string, number, or tuple.
-
How to copy a dictionary without linking it to the original?
Use the
.copy()method:original = {"x": 1} copy_dict = original.copy() -
What is the difference between the
get()method and direct access to the key?The
get()method allows you to set a default value and avoid errors if the key does not exist. -
How to remove multiple keys from a dictionary at once?
user = {"name": "Irina", "age": 29, "city": "Moscow"} keys_to_remove = ["age", "city"] for key in keys_to_remove: user.pop(key, None) # `None` prevents an error if the key is missing print(user) # {'name': 'Irina'} -
Can dictionary comprehensions be used?
Yes, here is an example:
squares = {x: x**2 for x in range(5)} print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Conclusion
Dictionaries in Python are a powerful and flexible tool for working with data. By mastering the basic and advanced operations with dictionaries, you can write more efficient and readable code. Practice, use the provided examples, and you will become a true master in working with data collections in Python!
The Future of AI in Mathematics and Everyday Life: How Intelligent Agents Are Already Changing the Game
Experts warned about the risks of fake charity with AI
In Russia, universal AI-agent for robots and industrial processes was developed