Stories
Culture & Landmarks
History & Heritage
Python Dictionary Methods
Master the essential methods for manipulating and working with Python Dictionaries efficiently.
clear()
Removes all elements from the dictionary
Example
Remove all items from the person dictionary:
person = {'name': 'Alice', 'age': 25, 'city': 'Paris'}
person.clear()
print(person)
# Output: {}
Definition and Usage
The clear() method removes all key–value pairs from a dictionary, leaving it empty.
Syntax
dict.clear()
Parameter Values
| Parameter | Description |
|---|---|
| None | This method takes no parameters. |
copy()
Returns a shallow copy of the dictionary
Example
Create a shallow copy of the person dictionary:
person = {'name': 'Alice', 'age': 25, 'city': 'Paris'}
person_copy = person.copy()
print(person_copy)
# Output: {'name': 'Alice', 'age': 25, 'city': 'Paris'}
Definition and Usage
The copy() method returns a shallow copy of the dictionary. Changes to the copy do not affect the original dictionary's top-level keys, but nested objects are still shared.
Syntax
dict.copy()
Parameter Values
| Parameter | Description |
|---|---|
| None | This method takes no parameters. |
fromkeys()
Creates a new dictionary with keys from a sequence and a given value
Example
Create a dictionary from a list of keys with the same value:
keys = ['name', 'age', 'city']
default_dict = dict.fromkeys(keys, 'unknown')
print(default_dict)
# Output: {'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}
Definition and Usage
The fromkeys() method creates a new dictionary with keys taken from an iterable (like a list or tuple) and assigns each key a specified value. If no value is provided, the default is None.
Syntax
dict.fromkeys(seq, value=None)
Parameter Values
| Parameter | Description |
|---|---|
seq |
Required An iterable (list, tuple, etc.) of keys for the new dictionary |
value |
Optional The value assigned to each key (default is None) |
get()
Returns the value for a key if it exists, otherwise a default value
Example
Retrieve the value for a key safely using get():
person = {'name': 'Alice', 'age': 25}
# Key exists
name = person.get('name')
print(name)
# Output: Alice
# Key does not exist, default used
city = person.get('city', 'Unknown')
print(city)
# Output: Unknown
Definition and Usage
The get() method returns the value associated with a key if it exists in the dictionary. If the key is not present, it returns the specified default value (or None if no default is provided).
Syntax
dict.get(key, default=None)
Parameter Values
| Parameter | Description |
|---|---|
key |
Required The key to look up in the dictionary |
default |
Optional The value returned if the key is not found (default is None) |
items()
Returns a view of the dictionary's key-value pairs
Example
Demonstrating iteration and view object behavior when the dictionary changes:
person = {'name': 'Alice', 'age': 25, 'city': 'Paris'}
# Get a view object of key-value pairs
kv_pairs = person.items()
print("View object:", kv_pairs)
# Output: dict_items([('name', 'Alice'), ('age', 25), ('city', 'Paris')])
# Iterate through key-value pairs
print("Iteration output:")
for key, value in kv_pairs:
print(f"{key}: {value}")
# Output:
# name: Alice
# age: 25
# city: Paris
# Modify the dictionary
person['age'] = 26
person['country'] = 'France'
# View object automatically reflects changes
print("\nUpdated view object:", kv_pairs)
# Output: dict_items([('name', 'Alice'), ('age', 26), ('city', 'Paris'), ('country', 'France')])
Definition and Usage
The items() method returns a **view object** displaying the dictionary's key-value pairs.
Iterating over it yields the current items, and if the dictionary changes, the view object reflects those changes automatically.
Syntax
dict.items()
Parameter Values
| Parameter | Description |
|---|---|
| None | This method takes no parameters. |
keys()
Returns a view of the dictionary's keys
Example
Demonstrating iteration and view object behavior for dictionary keys:
person = {'name': 'Alice', 'age': 25, 'city': 'Paris'}
# Get a view object of keys
keys_view = person.keys()
print("Keys view:", keys_view)
# Output: dict_keys(['name', 'age', 'city'])
# Iterate through keys
print("Iteration output:")
for key in keys_view:
print(key)
# Output:
# name
# age
# city
# Modify the dictionary
person['age'] = 26
person['country'] = 'France'
# Keys view automatically reflects changes
print("\nUpdated keys view:", keys_view)
# Output: dict_keys(['name', 'age', 'city', 'country'])
Definition and Usage
The keys() method returns a **view object** showing the dictionary's keys.
Iterating over it provides the current keys, and the view object automatically updates if the dictionary is modified.
Syntax
dict.keys()
Parameter Values
| Parameter | Description |
|---|---|
| None | This method takes no parameters. |
pop()
Removes the specified key and returns its value
Example
Remove a key and get its value:
person = {'name': 'Alice', 'age': 25, 'city': 'Paris'}
# Remove 'age' key
age_value = person.pop('age')
print("Removed value:", age_value)
# Output: 25
print("Updated dictionary:", person)
# Output: {'name': 'Alice', 'city': 'Paris'}
# Attempt to remove a non-existent key with default value
country_value = person.pop('country', 'Unknown')
print("Removed value or default:", country_value)
# Output: Unknown
# Attempt to remove a non-existent key without default raises KeyError
# person.pop('salary') # Uncommenting this will raise KeyError
Definition and Usage
The pop() method removes the specified key from the dictionary and returns its value.
If the key does not exist, it returns the provided default value. Without a default, it raises a KeyError.
Syntax
dict.pop(key, default=None)
Parameter Values
| Parameter | Description |
|---|---|
key |
Required The key to remove from the dictionary |
default |
Optional The value to return if the key does not exist (default is None) |
popitem()
Removes and returns the last inserted key-value pair
Example
Remove the last inserted key-value pair from the dictionary:
person = {'name': 'Alice', 'age': 25, 'city': 'Paris'}
# Remove last inserted item
last_item = person.popitem()
print("Removed item:", last_item)
# Output: ('city', 'Paris')
print("Updated dictionary:", person)
# Output: {'name': 'Alice', 'age': 25}
# Adding a new item and popping again
person['country'] = 'France'
new_item = person.popitem()
print("Removed item:", new_item)
# Output: ('country', 'France')
# Popping from an empty dictionary raises KeyError
# empty_dict = {}
# empty_dict.popitem() # Uncommenting this will raise KeyError
Definition and Usage
The popitem() method removes and returns the **last inserted key-value pair** as a tuple.
In Python 3.7+ dictionaries maintain insertion order.
Attempting to pop from an empty dictionary raises a KeyError.
Syntax
dict.popitem()
Parameter Values
| Parameter | Description |
|---|---|
| None | This method takes no parameters. |
setdefault()
Returns the value of a key; inserts the key with a default if it does not exist
Example
Retrieve a value or insert a default if the key does not exist:
person = {'name': 'Alice', 'age': 25}
# Key exists
name = person.setdefault('name', 'Unknown')
print("Name:", name)
# Output: Name: Alice
print("Dictionary after setdefault:", person)
# Output: {'name': 'Alice', 'age': 25}
# Key does not exist, default inserted
city = person.setdefault('city', 'Paris')
print("City:", city)
# Output: City: Paris
print("Dictionary after setdefault:", person)
# Output: {'name': 'Alice', 'age': 25, 'city': 'Paris'}
Definition and Usage
The setdefault() method returns the value of the specified key.
If the key does not exist in the dictionary, it inserts the key with the provided default value and then returns that value.
Syntax
dict.setdefault(key, default=None)
Parameter Values
| Parameter | Description |
|---|---|
key |
Required The key to look up or insert |
default |
Optional The value to insert if the key does not exist (default is None) |
update()
Updates the dictionary with key-value pairs from another dictionary or iterable
Example
Update a dictionary using another dictionary and key-value pairs:
person = {'name': 'Alice', 'age': 25}
# Update with another dictionary
person.update({'age': 26, 'city': 'Paris'})
print("Updated dictionary:", person)
# Output: {'name': 'Alice', 'age': 26, 'city': 'Paris'}
# Update with keyword arguments
person.update(country='France', profession='Engineer')
print("Updated dictionary:", person)
# Output: {'name': 'Alice', 'age': 26, 'city': 'Paris', 'country': 'France', 'profession': 'Engineer'}
Definition and Usage
The update() method adds key-value pairs from another dictionary or an iterable of key-value pairs to the dictionary.
Existing keys are overwritten with new values. You can also pass key-value pairs using keyword arguments.
Syntax
dict.update([other])
Parameter Values
| Parameter | Description |
|---|---|
other |
Optional Another dictionary or iterable of key-value pairs to update the dictionary with |
values()
Returns a view of the dictionary's values
Example
Get a view of all values and see how it updates when the dictionary changes:
person = {'name': 'Alice', 'age': 25, 'city': 'Paris'}
# Get a view object of values
values_view = person.values()
print("Values view:", values_view)
# Output: dict_values(['Alice', 25, 'Paris'])
# Iterate through values
print("Iteration output:")
for value in values_view:
print(value)
# Output:
# Alice
# 25
# Paris
# Modify the dictionary
person['age'] = 26
person['country'] = 'France'
# Values view automatically reflects changes
print("\nUpdated values view:", values_view)
# Output: dict_values(['Alice', 26, 'Paris', 'France'])
Definition and Usage
The values() method returns a **view object** of the dictionary’s values.
Iterating over it provides the current values, and if the dictionary is modified, the view object automatically reflects the changes.
Syntax
dict.values()
Parameter Values
| Parameter | Description |
|---|---|
| None | This method takes no parameters. |
🍪 We Value Your Privacy
We use cookies to enhance your browsing experience and analyze our traffic. By clicking "Accept All", you consent to our use of cookies. Learn more