Apprendre le Python #11 - Les Dictionnaires
Table of Contents
Introduction
In this tutorial, we will explore dictionaries in Python, a crucial data structure that allows you to store and manage data effectively. Dictionaries are versatile and enable you to work with key-value pairs, making data access and manipulation straightforward. This guide will help you understand how to create, access, and utilize dictionaries in your Python projects.
Step 1: Understanding Dictionaries
Dictionaries in Python are collections of key-value pairs. Here’s what you need to know:
-
Creation: You can create a dictionary using curly braces
{}
or thedict()
function.Example:
my_dict = { "name": "Alice", "age": 25, "city": "Paris" }
-
Keys and Values: Each key must be unique and immutable (like strings or numbers), while values can be of any data type.
Step 2: Accessing Dictionary Values
To retrieve values from a dictionary, use the key inside square brackets []
or the get()
method.
-
Using Square Brackets:
print(my_dict["name"]) # Outputs: Alice
-
Using the get() Method:
print(my_dict.get("age")) # Outputs: 25
Practical Tip
Using get()
is safer as it returns None
if the key doesn’t exist, avoiding potential errors.
Step 3: Modifying Dictionaries
You can easily update, add, or remove items in a dictionary.
-
Updating a Value:
my_dict["age"] = 26
-
Adding a New Key-Value Pair:
my_dict["profession"] = "Engineer"
-
Removing a Key-Value Pair: Use the
del
statement or thepop()
method.del my_dict["city"] # or my_dict.pop("profession")
Common Pitfall
Ensure that keys are unique within the same dictionary to avoid overwriting values unintentionally.
Step 4: Looping Through a Dictionary
You can iterate through a dictionary to access keys, values, or both.
-
Iterating Through Keys:
for key in my_dict: print(key)
-
Iterating Through Values:
for value in my_dict.values(): print(value)
-
Iterating Through Key-Value Pairs:
for key, value in my_dict.items(): print(f"{key}: {value}")
Step 5: Nesting Dictionaries
Dictionaries can contain other dictionaries, allowing for complex data structures.
Example:
employees = {
"emp1": {"name": "Alice", "age": 25},
"emp2": {"name": "Bob", "age": 30}
}
Real-World Application
Nesting is useful when dealing with structured data, such as JSON objects or database records.
Conclusion
Dictionaries are a powerful feature in Python that allows for efficient data management. By understanding how to create, access, modify, and iterate through dictionaries, you can improve your coding skills and handle data more effectively. As a next step, practice using dictionaries in various projects or try converting JSON data into dictionaries for more complex applications.