HPSC PGT(CS)- Python Subjective Series
Day 25
Syllabus Coverage
Dictionaries in Python
- Introduction to dictionaries, accessing items using keys, mutability (adding/modifying
items).
- Traversing dictionaries.
- Built-in functions: `len()`, `dict()`, `keys()`, `values()`, `items()`, `get()`, `update()`, `del`,
`clear()`, `fromkeys()`, `copy()`, `pop()`, `popitem()`, `setdefault()`, `max()`, `min()`, `count()`,
`sorted()`, `copy()`.
- Suggested programs: counting character frequency, creating employee dictionaries.
Question of the day:
1. What is the purpose of the get() method? How is it different from
direct key access? 5 M
2. Explain the use of update(), del, and clear() methods in dictionaries. 5
M
Program of the day:
1. Write a program to demonstrate the difference between shallow copy
(copy()) and direct assignment. 5M
2. Implement a program to remove a specified key using pop() and the
last inserted key using popitem(). 5M
1. What is the purpose of the get() method? How is it different from direct key access? (5
Marks)
Answer:
The get() method is used to safely access dictionary values without raising a KeyError if the
key doesn't exist.
• Syntax: dict.get(key, default_value)
• Difference from Direct Access (dict[key]):
Feature get() Direct Access (dict[key])
Key Existence Returns None or default value Raises KeyError
Use Case Safe access When key is guaranteed to exist
Default Value Customizable (2nd argument) Not applicable
Example:
grades = {"Alice": 90, "Bob": 85}
print(grades.get("Alice")) # Output: 90
print(grades.get("Charlie")) # Output: None
print(grades["Charlie"]) # Raises KeyError
2. Explain the use of update(), del, and clear() methods in dictionaries. (5 Marks)
Answer:
1. update(): Merges another dictionary or iterable into the current one.
dict1 = {"a": 1}; dict2 = {"b": 2}
dict1.update(dict2) # dict1 becomes {"a": 1, "b": 2}
2. del: Deletes a key-value pair.
del dict1["a"] # Removes key "a"
3. clear(): Removes all items from the dictionary.
dict1.clear() # dict1 becomes {}
Programming Solutions
1. Demonstrate Shallow Copy (copy()) vs Direct Assignment (5 M)
original = {"a": 1, "b": [2, 3]}
# Direct Assignment (References same object)
direct_ref = original
direct_ref["a"] = 100 # Modifies original
# Shallow Copy (New dictionary, but nested objects are shared)
shallow_copy = original.copy()
shallow_copy["b"][0] = 200 # Affects original's nested list
print("Original:", original)
print("Direct Reference:", direct_ref)
print("Shallow Copy:", shallow_copy)
Output:
Original: {'a': 100, 'b': [200, 3]}
Direct Reference: {'a': 100, 'b': [200, 3]}
Shallow Copy: {'a': 1, 'b': [200, 3]}
2. Remove Keys Using pop() and popitem() (5 M)
student = {"name": "Rahul", "age": 20, "grade": "A", "city": "Mumbai"}
# Remove specified key with pop()
age = student.pop("age") # Returns the value
print("Removed age:", age)
print("After pop('age'):", student)
# Remove last inserted key with popitem()
last_item = student.popitem() # Returns (key, value) tuple
print("Removed last item:", last_item)
print("After popitem():", student)
Output:
Removed age: 20
After pop('age'): {'name': 'Rahul', 'grade': 'A', 'city': 'Mumbai'}
Removed last item: ('city', 'Mumbai')
After popitem(): {'name': 'Rahul', 'grade': 'A'}