Working with Python Dictionaries
Learning Objectives
By the end of this module, students will be able to:
1. Create dictionaries in various forms.
2. Access values using keys.
3. Add new key-value pairs to dictionaries.
4. Update existing key-value pairs in dictionaries.
5. Delete key-value pairs from dictionaries.
Creating Dictionaries
Dictionaries in Python are created using curly braces {} or the dict() constructor.
Basic Syntax
# Creating a dictionary with curly braces
my_dict = {'key1': 'value1', 'key2': 'value2'}
# Using the dict() constructor
my_dict = dict(key1='value1', key2='value2')
Examples
1. Empty Dictionary
empty_dict = {}
2. Dictionary with Strings as Keys
user = {'name': 'Alice', 'age': 25}
3. Dictionary with Mixed Data Types
mixed_dict = {'id': 101, 'price': 49.99, 'available': True}
4. Dictionary Using Tuples as Keys
coordinates = {(0, 0): 'origin', (1, 1): 'point1'}
Accessing Dictionary Values
Access values using square brackets [] or the get() method.
Examples
1. Using Square Brackets
user = {'name': 'Alice', 'age': 25}
print(user['name']) # Output: Alice
coordinates = {(0, 0): 'origin', (1, 1): 'point1'}
print(coordinates[(0, 0)]) # Output: origin
print(coordinates[(1, 1)]) # Output: point1
2. Using get() Method
user = {'name': 'Alice', 'age': 25}
print(user.get('age')) # Output: 25
print(user.get('address', 'Not Found')) # Output: Not Found
Adding Items to a Dictionary
Add new key-value pairs by assigning a value to a key.
Example
# Adding a new key-value pair
user = {'name': 'Alice'}
user['age'] = 25
print(user) # Output: {'name': 'Alice', 'age': 25}
Adding Multiple Items
Use the update() method to add multiple items.
user = {'name': 'Alice'}
user.update({'age': 25, 'city': 'New York'})
print(user) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
Updating Items in a Dictionary
Update the value of an existing key by reassigning it or using the update() method.
Examples
1. Reassigning a Key
user = {'name': 'Alice', 'age': 25}
user['age'] = 26
print(user) # Output: {'name': 'Alice', 'age': 26}
2. Using update()
user = {'name': 'Alice', 'age': 25}
user.update({'age': 26, 'city': 'New York'})
print(user) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}
Deleting Items from a Dictionary
Dictionaries provide several ways to remove items.
Methods
1. Using pop() Removes a key-value pair and returns the value.
user = {'name': 'Alice', 'age': 25}
age = user.pop('age')
print(user) # Output: {'name': 'Alice'}
print(age) # Output: 25
2. Using del Statement Deletes a key-value pair.
user = {'name': 'Alice', 'age': 25}
del user['age']
print(user) # Output: {'name': 'Alice'}
3. Using clear() Removes all key-value pairs from the dictionary.
user = {'name': 'Alice', 'age': 25}
user.clear()
print(user) # Output: {}
Looping Through a Dictionary
Loop through keys, values, or both.
Examples
1. Keys Only
for key in user:
print(key)
2. Values Only
for value in user.values():
print(value)
3. Key-Value Pairs
for key, value in user.items():
print(f"{key}: {value}")
Summary of Key Operations
Operation Code Example Result
Create Dictionary my_dict = {'a': 1, 'b': 2} {'a': 1, 'b': 2}
Access Value my_dict['a'] or my_dict.get('a') 1
Add Item my_dict['c'] = 3 {'a': 1, 'b': 2, 'c': 3}
Update Value my_dict['b'] = 4 {'a': 1, 'b': 4, 'c': 3}
Delete Item del my_dict['b'] {'a': 1, 'c': 3}
Remove All Items my_dict.clear() {}
Practice Problems
1. Create a dictionary with three key-value pairs: 'fruit': 'apple', 'color': 'red', and 'price': 10.
2. Write code to access the value of the key 'color' in the dictionary.
3. Add a new key 'quantity' with the value 5 to the dictionary.
4. Update the value of 'price' to 12.
5. Remove the key 'fruit' using pop().
6. Clear all items in the dictionary.
Encourage students to test these operations in a Python IDE for hands-on experience.