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)