Advanced Dictionary Operations
This page covers more complex operations with Python dictionaries, including adding elements, using the items()
method, checking membership, and constructing dictionaries from other data structures.
Adding Elements
To add a new key-value pair to an existing dictionary, simply assign a value to a new key:
Example: Harry["Age"] = 19
The items() Method
The items()
method returns a list of key-value pairs:
Highlight: This method is particularly useful for iterating over both keys and values simultaneously.
Checking Membership
Use the in
keyword to check if a key exists in a dictionary:
Example: "Nom" in Harry
returns True
Constructing Dictionaries
From a Tuple
You can create a dictionary from a list of tuples:
Example:
liste = [("ete", "soleil"), ("hiver", "neige")]
mon_dict = dict(liste)
By Comprehension
Dictionary comprehension allows for concise dictionary creation:
Example:
dict_carre = {x: x**2 for x in range(5)}
This creates a dictionary where keys are numbers from 0 to 4, and values are their squares.
Vocabulary: Dictionary comprehension is a concise way to create dictionaries using a single line of code, similar to list comprehensions.
These advanced techniques demonstrate the flexibility and power of Python dictionaries, making them an essential tool for data manipulation in NSI coursework and the Épreuve pratique NSI 2024.