Core Dictionary Operations
Once you have created a dictionary, you will 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 retrieve a value associated with a specific key.
Bracket Notation []
Bracket Notation: dictionary[key]
This is the most direct way to access a value. You provide the key inside square brackets:
Example
Output:
KeyError Warning: If you use bracket notation to access a key that does not exist in the dictionary, Python will raise a KeyError and crash. Always verify keys or use the safe method below!
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 brand new key-value pair is created.
- If the key already exists, its old value is overwritten with the new one.
Let us see this in action:
Example
Output:
Initial user dictionary: {'id': 11}After adding keys: {'id': 11, 'email': 'user@example.com', 'active': True}After updating id: {'id': 15, 'email': 'user@example.com', 'active': True}
3. Merging Dictionaries
You will often need to combine two separate dictionaries together. Python offers several elegant ways to do this.
Key Overwriting: In both merging methods, if a key exists in both dictionaries, the value from the right-hand dictionary will overwrite the value from the left-hand one!
4. Removing Entries
Python provides several ways to remove items from a dictionary, each with unique behaviors.