Welcome to Day 26 of the 100 Days of Python series!
Now that you understand how dictionaries work (Day 25), it's time to explore the powerful built-in methods that make dictionaries even more flexible and efficient.
Let’s level up your skills and make you a dictionary ninja. 🥷🐍
📦 What You’ll Learn
- Essential dictionary methods like
get()
,update()
,pop()
, and more - How to safely access, merge, and manipulate key-value pairs
- Real-world examples using each method
🧠 Dictionary Recap
A dictionary is a collection of key-value pairs where:
- Keys must be unique and immutable (strings, numbers, tuples, etc.)
- Values can be any type
user = { "name": "Alice", "age": 30, "city": "Paris" }
🔍 1. get(key[, default])
– Safe Access
print(user.get("age")) # 30 print(user.get("email")) # None print(user.get("email", "N/A")) # N/A
✅ Prevents crashes when a key doesn’t exist.
➕ 2. update(other_dict)
– Merge Dictionaries
user.update({"email": "alice@example.com"}) print(user) # {'name': 'Alice', 'age': 30, 'city': 'Paris', 'email': 'alice@example.com'}
✅ Also overrides values if keys already exist.
user.update({"age": 31}) # Updates age from 30 to 31
❌ 3. pop(key[, default])
– Remove and Return Value
age = user.pop("age") print(age) # 31 print(user) # 'age' key is gone
Add a default to avoid error if key is missing:
email = user.pop("email", "not found")
🚫 4. popitem()
– Remove Last Added Pair (Python 3.7+)
last = user.popitem() print(last) # ('email', 'alice@example.com')
✅ Useful when treating a dict like a stack.
🧽 5. clear()
– Remove All Items
user.clear() print(user) # {}
🆕 6. setdefault(key[, default])
– Get or Set Default Value
settings = {"theme": "dark"} theme = settings.setdefault("theme", "light") # Keeps existing lang = settings.setdefault("language", "English") # Adds key print(settings) # {'theme': 'dark', 'language': 'English'}
✅ Great for initializing nested or optional fields.
📋 7. keys()
, values()
, items()
print(user.keys()) # dict_keys(['name', 'city']) print(user.values()) # dict_values(['Alice', 'Paris']) print(user.items()) # dict_items([('name', 'Alice'), ('city', 'Paris')])
Useful in loops:
for key in user.keys(): print(key) for value in user.values(): print(value) for key, value in user.items(): print(f"{key} = {value}")
🔎 8. in
Keyword – Key Existence
if "name" in user: print("User has a name")
Note: Only checks keys, not values.
🧪 Real-World Example: Counting Words
sentence = "apple banana apple orange banana apple" counts = {} for word in sentence.split(): counts[word] = counts.get(word, 0) + 1 print(counts) # {'apple': 3, 'banana': 2, 'orange': 1}
✅ get()
avoids checking if key in dict
first.
📄 Example: Nested Initialization with setdefault()
students = {} students.setdefault("john", {})["math"] = 90 students.setdefault("john", {})["science"] = 85 print(students) # {'john': {'math': 90, 'science': 85}}
📌 Summary of Methods
Method | Description |
---|---|
get() | Returns value or default if key missing |
update() | Merges another dictionary |
pop() | Removes and returns value of key |
popitem() | Removes and returns last inserted item |
clear() | Empties the dictionary |
setdefault() | Gets or sets a default value |
keys() | Returns a view of all keys |
values() | Returns a view of all values |
items() | Returns a view of all key-value pairs |
🧠 Recap
Today you learned:
- The most powerful dictionary methods and how to use them
- How to safely get values and set defaults
- How to merge dictionaries, pop values, and loop through items
- Real-world use cases like frequency counters and nested defaults
Top comments (0)