■ Understanding Special Dictionary Methods in Python
Python dictionaries come with some powerful methods to make our coding easier. Two important
ones are fromkeys() and setdefault().
------------------------------------------------------ ■ 1. fromkeys() — Creating a Dictionary from a List of
Keys
Definition: fromkeys() is used to create a new dictionary from a list (or tuple) of keys, with a
common default value for all keys.
Syntax: dictionary_name = [Link](keys, value)
- keys: a list or tuple of keys - value: a single default value assigned to all keys (optional; default is
None)
■ Real-World Example: Attendance Tracker
students = ["Asha", "Rahul", "Sneha", "Kiran"] attendance = [Link](students, "Absent")
print(attendance)
Output: {'Asha': 'Absent', 'Rahul': 'Absent', 'Sneha': 'Absent', 'Kiran': 'Absent'}
attendance["Asha"] = "Present" print(attendance)
Output: {'Asha': 'Present', 'Rahul': 'Absent', 'Sneha': 'Absent', 'Kiran': 'Absent'}
Why useful? Quickly create a dictionary with same default values — great for things like: -
initializing status - marking default settings - setting counters to zero
------------------------------------------------------ ■ 2. setdefault() — Safe Value Retrieval and
Assignment
Definition: setdefault() is used to: 1. Get a value for a given key if it exists. 2. Insert the key with a
default value if it doesn’t exist.
Syntax: dictionary_name.setdefault(key, default_value)
If the key exists → returns its value. If not → adds the key with the given default value.
■ Real-World Example: Customer Loyalty Points
loyalty_points = {"Rahul": 120, "Sneha": 90}
# New customer points = loyalty_points.setdefault("Asha", 0) print("Asha’s points:", points)
print("Updated dictionary:", loyalty_points)
Output: Asha’s points: 0 Updated dictionary: {'Rahul': 120, 'Sneha': 90, 'Asha': 0}
# Existing customer points = loyalty_points.setdefault("Rahul", 0) print(points)
Output: 120
Why useful? - Prevents errors if a key doesn’t exist - Helps in building counting or grouping
systems safely
------------------------------------------------------ ■ Summary Table
| Method | Purpose | Example Use Case | Default Behavior |
|--------|----------|------------------|------------------| | fromkeys() | Creates new dictionary with same default
value for all keys | Marking attendance, initializing settings | Returns new dictionary | | setdefault() |
Returns value of key; adds key with default if missing | Loyalty points, counters | Modifies original
dictionary |
------------------------------------------------------ ■ Quick Practice
fruits = ["Apple", "Banana", "Mango"] stock = [Link](fruits, 0)
[Link]("Apple", 10) [Link]("Orange", 5)
print(stock)
Can you predict the output? ■■■