← Back to Python Course | Chapter 6: Data Structures | Lesson 7 of 12

Python Dictionary Methods

Retrieving Keys, Values, and Items

keys(), values(), and items() return live, dynamic views rather than static copies, meaning they automatically reflect later changes to the dictionary; items() returning (key, value) tuples is what makes 'for k, v in d.items()' the standard iteration pattern.

Example: Retrieving Keys, Values, and Items

python
user = {"name": "Alex", "age": 30}
print(list(user.keys()))
print(list(user.values()))
print(list(user.items()))

Safe Lookups with get()

get(key, default) looks up a key without ever raising KeyError -- if the key is missing it returns None (or your specified default) instead, which is safer than square-bracket access whenever a key's presence isn't guaranteed.

Example: Safe Lookups with get()

python
user = {"name": "Alex"}
print(user.get("age"))
print(user.get("age", 0))

Removing Items with pop()

pop(key) removes that key and returns its value (optionally with a default to avoid KeyError on a missing key), while popitem() removes and returns the most recently inserted (key, value) pair as a tuple -- useful for treating a dict like a stack.

Example: Removing Items with pop()

python
user = {"name": "Alex", "age": 30}
age = user.pop("age")
print(age, user)

Updating and Merging

update() merges another dictionary or an iterable of key-value pairs into the current one in place; matching keys get overwritten with the new values while unmatched keys from the current dict are left untouched.

Example: Updating and Merging

python
user = {"name": "Alex", "age": 30}
user.update({"age": 31, "city": "NYC"})
print(user)

Default Values and Clearing

setdefault(key, default) returns the existing value if the key is present, or inserts the key with the given default and returns that -- a compact one-line replacement for the common 'if key not in d: d[key] = default' pattern. clear() empties the dictionary entirely.

Example: Default Values and Clearing

python
user = {"name": "Alex"}
user.setdefault("age", 18)
print(user)
user.clear()
print(user)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.