Core Dictionary Operations
Once you’ve created a dictionary, you’ll need to interact with it. The core operations involve accessing, adding, updating, and removing key-value pairs. Mastering these patterns is essential for effectively using dictionaries in your programs.
1. Accessing Values
There are two primary ways to get a value associated with a key.
Bracket Notation: dictionary[key]
This is the most direct way to access a value. You provide the key inside square brackets.
Pyground
Create a user profile and access the user's name and role using bracket notation.
Expected Output:
Name: Nisha Singh Role: Designer
Output:
KeyError: If you use bracket notation to access a key that does not exist in the dictionary, Python will raise a KeyError
. This can crash your program if not handled properly.
2. Adding and Updating Entries
You can add a new key-value pair or update an existing one using simple bracket assignment.
- If the key does not exist, a new key-value pair is created.
- If the key already exists, its value is updated.
Pyground
Start with a user profile containing an 'id'. Add an 'email' and 'active' status, then update the 'id'.
Expected Output:
Initial user: {'id': 11} After adding keys: {'id': 11, 'email': 'user@example.com', 'active': True} After updating id: {'id': 15, 'email': 'user@example.com', 'active': True}
Output:
3. Merging Dictionaries
You often need to combine two dictionaries. Python offers several ways to do this.
The Merge |
Operator (Python 3.9+)
This modern syntax is clean and expressive. It creates a new dictionary containing the items from both.
Pyground
Merge a base configuration with an override configuration using the `|` operator.
Expected Output:
{'host': 'api.example.com', 'port': 443, 'protocol': 'https'}
Output:
Key Precedence: In both merging methods, if a key exists in both dictionaries, the value from the right-hand dictionary (the one being merged in) will overwrite the value in the left-hand one.
4. Removing Entries
There are several ways to remove items from a dictionary, each with different behaviors.
del
Keyword
del
removes a key-value pair. It’s simple but will raise a KeyError
if the key doesn’t exist.
user = {"name": "Riya", "plan": "pro", "id": 30}
del user["plan"]
print(user) # Output: {'name': 'Riya', 'id': 30}
# del user["plan"] # Would raise KeyError now