DEV Community

Cover image for Day 26/100: Dictionary Methods in Python (get(), update(), and More)
 Rahul Gupta
Rahul Gupta

Posted on

Day 26/100: Dictionary Methods in Python (get(), update(), and More)

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"
}
Enter fullscreen mode Exit fullscreen mode

πŸ” 1. get(key[, default]) – Safe Access

print(user.get("age"))         # 30
print(user.get("email"))       # None
print(user.get("email", "N/A"))  # N/A
Enter fullscreen mode Exit fullscreen mode

βœ… 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'}
Enter fullscreen mode Exit fullscreen mode

βœ… Also overrides values if keys already exist.

user.update({"age": 31})  # Updates age from 30 to 31
Enter fullscreen mode Exit fullscreen mode

❌ 3. pop(key[, default]) – Remove and Return Value

age = user.pop("age")
print(age)   # 31
print(user)  # 'age' key is gone
Enter fullscreen mode Exit fullscreen mode

Add a default to avoid error if key is missing:

email = user.pop("email", "not found")
Enter fullscreen mode Exit fullscreen mode

🚫 4. popitem() – Remove Last Added Pair (Python 3.7+)

last = user.popitem()
print(last)   # ('email', 'alice@example.com')
Enter fullscreen mode Exit fullscreen mode

βœ… Useful when treating a dict like a stack.


🧽 5. clear() – Remove All Items

user.clear()
print(user)  # {}
Enter fullscreen mode Exit fullscreen mode

πŸ†• 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'}
Enter fullscreen mode Exit fullscreen mode

βœ… 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')])
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

πŸ”Ž 8. in Keyword – Key Existence

if "name" in user:
    print("User has a name")
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

βœ… 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}}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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)