- keys() — get all keys in a dictionary
- values() — get all values in a dictionary
- items() — get all key-value pairs
- get() — safely retrieve values
- update() — merge dictionaries
- pop() — remove and return values
- popitem() — remove last item
- clear() — remove all items
- copy() — create a copy
- fromkeys() — create from keys
Introduction to Dictionary Methods
Python dictionaries provide a rich set of built-in methods for performing various operations. These methods can be categorized into several groups:
- View methods:
keys(),values(),items() - Access methods:
get(),setdefault() - Modification methods:
update(),pop(),popitem(),clear() - Utility methods:
copy(),fromkeys()
Most dictionary methods modify the dictionary in place, meaning they change the original dictionary rather than creating a new one.
💡 Key concept: Dictionary view objects (keys(), values(), items()) provide a dynamic view of the dictionary. Changes to the dictionary are reflected in the view.
keys() — Get All Keys
Accessing All Keys
The keys() method returns a view object containing all the keys in the dictionary. This view is dynamic and reflects changes to the dictionary.
# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
keys = person.keys()
print(keys) # dict_keys(['name', 'age', 'city'])
# Converting to a list
keys_list = list(person.keys())
print(keys_list) # ['name', 'age', 'city']
# Iterating over keys
for key in person.keys():
print(f"Key: {key}")
# Dynamic view (reflects changes)
person["email"] = "alice@example.com"
print(keys) # dict_keys(['name', 'age', 'city', 'email'])
# Checking if a key exists
if "name" in person.keys():
print("Name key exists")
# Using with set operations
keys_set = set(person.keys())
print(keys_set) # {'name', 'age', 'city', 'email'}
Characteristics:
- Returns a view object (dynamic)
- Reflects changes to the dictionary
- Can be converted to a list or set
- Time complexity: O(1) to get the view, O(n) to iterate
Quick Check: What type of object does keys() return? (Answer: A view object)
values() — Get All Values
Accessing All Values
The values() method returns a view object containing all the values in the dictionary. This view is dynamic and reflects changes to the dictionary.
# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
values = person.values()
print(values) # dict_values(['Alice', 25, 'NYC'])
# Converting to a list
values_list = list(person.values())
print(values_list) # ['Alice', 25, 'NYC']
# Iterating over values
for value in person.values():
print(f"Value: {value}")
# Dynamic view
person["email"] = "alice@example.com"
print(values) # dict_values(['Alice', 25, 'NYC', 'alice@example.com'])
# Checking if a value exists
if "Alice" in person.values():
print("Alice is in the dictionary")
# Using with set operations (values may not be hashable)
values_set = set(person.values()) # Works if all values are hashable
Characteristics:
- Returns a view object (dynamic)
- Reflects changes to the dictionary
- May contain duplicate values
- Can be converted to a list or set
Quick Check: Can values() contain duplicate values? (Answer: Yes, because values are not required to be unique)
items() — Get Key-Value Pairs
Accessing All Key-Value Pairs
The items() method returns a view object containing all key-value pairs as tuples. This is the most commonly used method for iterating over dictionaries.
# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
items = person.items()
print(items) # dict_items([('name', 'Alice'), ('age', 25), ('city', 'NYC')])
# Converting to a list
items_list = list(person.items())
print(items_list) # [('name', 'Alice'), ('age', 25), ('city', 'NYC')]
# Iterating over items (most common)
for key, value in person.items():
print(f"{key}: {value}")
# Dynamic view
person["email"] = "alice@example.com"
print(items) # dict_items([('name', 'Alice'), ('age', 25), ('city', 'NYC'), ('email', 'alice@example.com')])
# Using in a list comprehension
keys_values = [(k, v) for k, v in person.items()]
print(keys_values)
# Filtering items
filtered = {k: v for k, v in person.items() if v is not None}
print(filtered)
Characteristics:
- Returns a view object of (key, value) tuples
- Dynamic — reflects changes to the dictionary
- Most common method for iteration
- Can be used in comprehensions
Quick Check: What does items() return when iterated? (Answer: (key, value) tuples)
get() — Safe Value Retrieval
Retrieving Values Safely
The get() method retrieves a value for a given key. If the key doesn't exist, it returns a default value (or None) instead of raising an error.
# Basic usage
person = {"name": "Alice", "age": 25}
print(person.get("name")) # Alice
print(person.get("city")) # None
print(person.get("city", "Unknown")) # Unknown
# Using with default values
config = {"host": "localhost", "port": 8080}
print(config.get("host", "127.0.0.1")) # localhost
print(config.get("timeout", 30)) # 30
# In a loop
keys = ["name", "age", "city", "country"]
for key in keys:
value = person.get(key, "Not found")
print(f"{key}: {value}")
# Practical use: counting with get()
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts) # {'apple': 3, 'banana': 2, 'cherry': 1}
Characteristics:
- Returns the value if the key exists
- Returns
Noneor a default value if the key doesn't exist - No error is raised
- Ideal for safe data retrieval
Quick Check: What does get() return if the key is not found? (Answer: None or the specified default value)
update() — Merge Dictionaries
Merging Dictionaries
The update() method merges another dictionary or iterable of key-value pairs into the current dictionary. If keys already exist, their values are updated.
# Basic usage
person = {"name": "Alice", "age": 25}
person.update({"city": "NYC", "age": 26})
print(person) # {'name': 'Alice', 'age': 26, 'city': 'NYC'}
# Merging with another dictionary
data1 = {"a": 1, "b": 2}
data2 = {"b": 3, "c": 4}
data1.update(data2)
print(data1) # {'a': 1, 'b': 3, 'c': 4}
# Using with keyword arguments
person.update(email="alice@example.com", phone="555-1234")
print(person) # {'name': 'Alice', 'age': 26, 'city': 'NYC', 'email': 'alice@example.com', 'phone': '555-1234'}
# Using with a list of tuples
person.update([("city", "LA"), ("age", 27)])
print(person) # {'name': 'Alice', 'age': 27, 'city': 'LA', 'email': 'alice@example.com', 'phone': '555-1234'}
# Using with zip()
keys = ["a", "b", "c"]
values = [1, 2, 3]
my_dict = {}
my_dict.update(zip(keys, values))
print(my_dict) # {'a': 1, 'b': 2, 'c': 3}
Characteristics:
- Modifies the dictionary in place
- Accepts another dictionary, list of tuples, or keyword arguments
- Returns
None - Overwrites existing keys with new values
Quick Check: Does update() return a new dictionary? (Answer: No — it modifies the original in place)
pop() — Remove and Return
Removing a Key-Value Pair
The pop() method removes the specified key from the dictionary and returns its value. If the key doesn't exist, it returns a default value or raises KeyError.
# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
age = person.pop("age")
print(age) # 25
print(person) # {'name': 'Alice', 'city': 'NYC'}
# Using with a default value
city = person.pop("city", "Unknown")
print(city) # NYC
country = person.pop("country", "USA")
print(country) # USA
# Without a default (raises KeyError)
# person.pop("country") # KeyError: 'country'
# Safe popping
key_to_remove = "city"
if key_to_remove in person:
value = person.pop(key_to_remove)
print(f"Removed: {value}")
else:
print("Key not found")
# Using pop in a loop
person = {"name": "Alice", "age": 25, "city": "NYC", "email": "alice@example.com"}
for key in list(person.keys()):
if key != "name":
person.pop(key)
print(person) # {'name': 'Alice'}
Characteristics:
- Removes and returns the value for the specified key
- Raises
KeyErrorif the key doesn't exist (no default) - Accepts an optional default value
- Modifies the dictionary in place
Quick Check: What does pop() return? (Answer: The value of the removed key)
popitem() — Remove Last Item
Removing and Returning the Last Item
The popitem() method removes and returns the last inserted key-value pair from the dictionary. In Python 3.7+, this follows insertion order.
# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
item = person.popitem()
print(item) # ('city', 'NYC')
print(person) # {'name': 'Alice', 'age': 25}
# Removing all items using popitem()
person = {"name": "Alice", "age": 25, "city": "NYC"}
while person:
key, value = person.popitem()
print(f"Removed: {key} -> {value}")
print(person) # {}
# popitem() on an empty dictionary
# empty = {}
# empty.popitem() # KeyError: 'popitem(): dictionary is empty'
# Safe popitem with checking
if person:
key, value = person.popitem()
print(f"Removed: {key} -> {value}")
else:
print("Dictionary is empty")
Characteristics:
- Removes and returns the last inserted item
- In Python 3.7+, follows insertion order
- Raises
KeyErrorif the dictionary is empty - Modifies the dictionary in place
Quick Check: What does popitem() return? (Answer: A (key, value) tuple)
clear() — Remove All
Removing All Key-Value Pairs
The clear() method removes all key-value pairs from the dictionary, leaving it empty.
# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
print(f"Before clear: {person}")
person.clear()
print(f"After clear: {person}") # {}
# Checking if the dictionary is empty
if not person:
print("Dictionary is empty")
# Clearing a dictionary in a loop
data = {"a": 1, "b": 2, "c": 3}
for key in list(data.keys()):
data.pop(key)
print(data) # {}
# Alternative: reassign to empty dictionary
data = {"a": 1, "b": 2, "c": 3}
data = {} # Creates a new empty dictionary
Characteristics:
- Removes all key-value pairs
- Modifies the dictionary in place
- Returns
None - Useful for resetting a dictionary
Quick Check: What does clear() return? (Answer: None — it modifies the dictionary in place)
copy() — Create a Copy
Creating a Shallow Copy
The copy() method creates a shallow copy of the dictionary. Changes to the copy do not affect the original dictionary.
# Basic usage
person = {"name": "Alice", "age": 25, "city": "NYC"}
copy = person.copy()
print(copy) # {'name': 'Alice', 'age': 25, 'city': 'NYC'}
# Copy vs direct assignment
person = {"name": "Alice", "age": 25}
copy = person.copy() # Creates a new dictionary
reference = person # Reference to the same dictionary
copy["age"] = 30
reference["age"] = 35
print(person) # {'name': 'Alice', 'age': 35} (reference changed)
print(copy) # {'name': 'Alice', 'age': 30} (copy unaffected)
# Shallow copy with nested dictionaries
person = {"name": "Alice", "address": {"city": "NYC"}}
copy = person.copy()
copy["address"]["city"] = "LA"
print(person) # {'name': 'Alice', 'address': {'city': 'LA'}} — nested changed!
# For deep copy, use copy module
import copy
person = {"name": "Alice", "address": {"city": "NYC"}}
deep_copy = copy.deepcopy(person)
deep_copy["address"]["city"] = "LA"
print(person) # {'name': 'Alice', 'address': {'city': 'NYC'}} — unchanged
Characteristics:
- Creates a shallow copy of the dictionary
- Nested objects are not copied (they are referenced)
- Use
copy.deepcopy()for deep copies - Modifications to the copy don't affect the original
Quick Check: Does copy() create a deep copy? (Answer: No — it creates a shallow copy)
fromkeys() — Create from Keys
Creating a Dictionary from Keys
The fromkeys() class method creates a new dictionary from a sequence of keys, all with the same default value.
# Basic usage
keys = ["name", "age", "city"]
person = dict.fromkeys(keys)
print(person) # {'name': None, 'age': None, 'city': None}
# With a default value
person = dict.fromkeys(keys, "unknown")
print(person) # {'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}
# Using with a list
keys = [1, 2, 3]
data = dict.fromkeys(keys, 0)
print(data) # {1: 0, 2: 0, 3: 0}
# Using with a tuple
keys = ("a", "b", "c")
data = dict.fromkeys(keys, [])
print(data) # {'a': [], 'b': [], 'c': []}
# Note: using mutable default values
data = dict.fromkeys(keys, [])
data["a"].append(1)
print(data) # {'a': [1], 'b': [1], 'c': [1]} — all share the same list!
# To avoid this, use a comprehension
data = {key: [] for key in keys}
data["a"].append(1)
print(data) # {'a': [1], 'b': [], 'c': []}
Characteristics:
- Creates a new dictionary from keys
- All keys have the same initial value
- Works with any iterable of keys
- Warning: Mutable default values are shared
Quick Check: What is the default value when using fromkeys() without specifying one? (Answer: None)
Common Mistakes
Watch Out For These!
Mistake 1: Using pop() Without Checking Key Existence
# WRONG — raises KeyError
person = {"name": "Alice", "age": 25}
# person.pop("city") # KeyError
# CORRECT — use a default value
city = person.pop("city", "Unknown")
print(city) # Unknown
Mistake 2: Assuming copy() Creates a Deep Copy
# WRONG — nested dictionaries are shared
person = {"name": "Alice", "address": {"city": "NYC"}}
copy = person.copy()
copy["address"]["city"] = "LA"
print(person) # {'name': 'Alice', 'address': {'city': 'LA'}}
# CORRECT — use deepcopy
import copy
deep_copy = copy.deepcopy(person)
Mistake 3: Using fromkeys() with Mutable Default Values
# WRONG — all keys share the same list
keys = ["a", "b", "c"]
data = dict.fromkeys(keys, [])
data["a"].append(1)
print(data) # {'a': [1], 'b': [1], 'c': [1]}
# CORRECT — use a comprehension
data = {key: [] for key in keys}
Quick Check: What is the most common mistake with fromkeys()? (Answer: Using mutable default values — they are shared across all keys)
Interactive Editor
Experiment with dictionary methods directly in your browser. Modify the code and see the results in real time.
DICTIONARY METHODS PRACTICE
========================================
Original: {'name': 'Alice', 'age': 25, 'city': 'NYC'}
1. KEYS()
Keys: ['name', 'age', 'city']
2. VALUES()
Values: ['Alice', 25, 'NYC']
3. ITEMS()
name: Alice
age: 25
city: NYC
4. GET()
get('name'): Alice
get('country', 'USA'): USA
5. UPDATE()
After update: {'name': 'Alice', 'age': 26, 'city': 'NYC', 'email': 'alice@example.com'}
6. POP()
Removed email: alice@example.com
After pop: {'name': 'Alice', 'age': 26, 'city': 'NYC'}
7. POPITEM()
Removed item: ('city', 'NYC')
After popitem: {'name': 'Alice', 'age': 26}
8. FROMKEYS()
From keys: {'x': 0, 'y': 0, 'z': 0}
9. CLEAR()
After clear: {}
Dictionary methods practice complete!
Certificate of Completion
You have completed the Python Dictionary Methods tutorial. You understand keys(), values(), items(), get(), update(), pop(), popitem(), clear(), copy(), and fromkeys() methods.
Quick Quiz — Test Your Knowledge
Let's see what you've learned about dictionary methods:
Frequently Asked Questions
What is the difference between keys() and items()?
keys() returns only the keys, while items() returns key-value pairs as tuples. Use items() when you need both keys and values.
What is the difference between get() and dict[key]?
dict[key] raises a KeyError if the key doesn't exist. get() returns None or a default value, without raising an error.
Does update() modify the original dictionary?
update() modifies the dictionary in place and returns None.
What is the difference between copy() and deepcopy()?
copy() creates a shallow copy (nested objects are shared). deepcopy() creates a recursive copy (nested objects are also copied).
What is the default value in fromkeys()?
None if not specified: dict.fromkeys(keys).
Can I use pop() on an empty dictionary?
pop() requires a key argument. On an empty dictionary, it raises KeyError for any key. popitem() raises KeyError on an empty dictionary.
Where to Go From Here
After mastering dictionary methods, consider exploring these related topics:
Iterate Dictionary
Learn different ways to loop through dictionaries.
Learn More →Formatting Dictionaries
Learn how to format and display dictionaries.
Learn More →Nested Dictionaries
Work with dictionaries within dictionaries.
Learn More →