Dictionaries-Module
Dictionaries-Module
Learning Objectives
By the end of this module, students will be able to:
Creating Dictionaries
Dictionaries in Python are created using curly braces {} or the dict() constructor.
Basic Syntax
Examples
1. Empty Dictionary
empty_dict = {}
Examples
print(user.get('age')) # Output: 25
Example
user['age'] = 25
Examples
1. Reassigning a Key
user['age'] = 26
2. Using update()
Methods
age = user.pop('age')
print(age) # Output: 25
del user['age']
user.clear()
print(user) # Output: {}
Looping Through a Dictionary
Loop through keys, values, or both.
Examples
1. Keys Only
print(key)
2. Values Only
print(value)
3. Key-Value Pairs
print(f"{key}: {value}")
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.
Encourage students to test these operations in a Python IDE for hands-on experience.