Python – Dictionary Methods
Python dictionaries come with a variety of built-in methods that allow you to perform various operations, such as adding, modifying, removing, and accessing data. Below is a list of some common dictionary methods:
1. clear()
The clear() method removes all items from the dictionary, leaving it empty.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear()
print(my_dict) # Output: {}
2. copy()
The copy() method returns a shallow copy of the dictionary. This means the new dictionary is a copy, but nested objects inside the dictionary will still reference the same objects.
Example:
original_dict = {'a': 1, 'b': 2}
copied_dict = original_dict.copy()
print(copied_dict) # Output: {'a': 1, 'b': 2}
3. get()
The get() method retrieves the value for the specified key. If the key is not found, it returns None (or a specified default value).
Example:
my_dict = {'a': 1, 'b': 2}
value = my_dict.get('b')
print(value) # Output: 2
# Using default value
value = my_dict.get('c', 'Not Found')
print(value) # Output: Not Found
4. items()
The items() method returns a view object that displays a list of the dictionary’s key-value tuple pairs.
Example:
my_dict = {'a': 1, 'b': 2}
for key, value in my_dict.items():
print(key, value)
# Output:
# a 1
# b 2
5. keys()
The keys() method returns a view object that displays a list of all the dictionary’s keys.
Example:
my_dict = {'a': 1, 'b': 2}
print(my_dict.keys()) # Output: dict_keys(['a', 'b'])
6. pop()
The pop() method removes the item with the specified key and returns its value. If the key is not found, it raises a KeyError, unless a default value is provided.
Example:
my_dict = {'a': 1, 'b': 2}
value = my_dict.pop('a')
print(value) # Output: 1
print(my_dict) # Output: {'b': 2}
# Using default value
value = my_dict.pop('c', 'Not Found')
print(value) # Output: Not Found
7. popitem()
The popitem() method removes and returns the last inserted key-value pair from the dictionary as a tuple. If the dictionary is empty, it raises a KeyError.
Example:
my_dict = {'a': 1, 'b': 2}
item = my_dict.popitem()
print(item) # Output: ('b', 2)
print(my_dict) # Output: {'a': 1}
8. setdefault()
The setdefault() method returns the value of the specified key. If the key doesn’t exist, it inserts the key with a specified default value and returns that value.
Example:
my_dict = {'a': 1, 'b': 2}
value = my_dict.setdefault('c', 3)
print(value) # Output: 3
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
9. update()
The update() method updates the dictionary with elements from another dictionary or from an iterable of key-value pairs.
Example:
my_dict = {'a': 1, 'b': 2}
my_dict.update({'b': 3, 'c': 4})
print(my_dict) # Output: {'a': 1, 'b': 3, 'c': 4}
# Using an iterable of tuples
my_dict.update([('d', 5), ('e', 6)])
print(my_dict) # Output: {'a': 1, 'b': 3, 'c': 4, 'd': 5, 'e': 6}
10. values()
The values() method returns a view object that displays a list of all the dictionary’s values.
Example:
my_dict = {'a': 1, 'b': 2}
print(my_dict.values()) # Output: dict_values([1, 2])
11. fromkeys()
The fromkeys() method returns a new dictionary with keys from the provided iterable and values set to a specified default value.
Example:
keys = ['a', 'b', 'c']
default_value = 0
new_dict = dict.fromkeys(keys, default_value)
print(new_dict) # Output: {'a': 0, 'b': 0, 'c': 0}
12. del
The del keyword can be used to delete a specific key-value pair from the dictionary.
Example:
my_dict = {'a': 1, 'b': 2}
del my_dict['a']
print(my_dict) # Output: {'b': 2}
Summary of Common Dictionary Methods:
clear(): Removes all items from the dictionary.copy(): Returns a shallow copy of the dictionary.get(): Retrieves a value by key, with an optional default value.items(): Returns key-value pairs as tuples.keys(): Returns all keys in the dictionary.pop(): Removes a key-value pair and returns the value.popitem(): Removes and returns the last inserted key-value pair.setdefault(): Returns the value of a key, or sets and returns a default value if the key doesn’t exist.update(): Updates the dictionary with key-value pairs from another dictionary or iterable.values(): Returns all values in the dictionary.fromkeys(): Creates a new dictionary from a list of keys with a default value.del: Deletes a key-value pair from the dictionary.