Python provides several built-in methods to manipulate dictionaries:
Common Dictionary Methods
- clear(): Removes all items from the dictionary.
- copy(): Returns a shallow copy of the dictionary.
- get(key, default): Returns the value for the specified key. If the key is not found, returns the default value (None if not specified).
- items(): Returns a view object of the dictionary’s key-value pairs as tuples.
- keys(): Returns a view object of the dictionary’s keys.
- pop(key[, default]): Removes and returns the item with the specified key. If the key is not found, returns the default value (raises a KeyError if not specified).
- popitem(): Removes and returns an arbitrary (key, value) pair as a tuple.
- setdefault(key, default): Returns the value for the specified key. If the key is not found, inserts the key with the default value and returns the default value.
- update([otherdict]): Updates the dictionary with the key-value pairs from another dictionary or an iterable.
- values(): Returns a view object of the dictionary’s values.
Example
Python
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Add a new key-value pair
my_dict['occupation'] = 'engineer'
# Get the value for a key
print(my_dict.get('address', 'Unknown')) # Output: Unknown
# Remove a key-value pair
my_dict.pop('age')
# Get all keys
print(my_dict.keys()) # Output: dict_keys(['name', 'city', 'occupation'])
# Get all values
print(my_dict.values()) # Output: dict_values(['Alice', 'New York', 'engineer'])
What are dictionary methods?
Dictionary methods are functions built into dictionary objects that allow you to manipulate and access data.
How do I add a new key-value pair to a dictionary?
Use assignment: dictionary_name[new_key] = new_value
.
What does the pop()
method do?
Removes and returns the item with the specified key.
What does the update()
method do?
Updates the dictionary with key-value pairs from another dictionary or an iterable.
What is the difference between keys()
and values()
?
keys()
returns a view of the dictionary’s keys, while values()
returns a view of the dictionary’s values.
Can I modify a dictionary while iterating over it?
It’s generally not recommended to modify a dictionary while iterating over it.
Are dictionary methods case-sensitive?
Yes, dictionary methods are case-sensitive.