Python Dictionary Methods Example
Python Dictionary Methods and Functions
Dictionaries in Python are mutable mappings of keys to values. They come with several methods
that help in managing the keys, values, and items. Below are the commonly used dictionary
methods along with examples.
1. clear() - Removes all items from the dictionary.
Example:
dict_example = {'a': 1, 'b': 2, 'c': 3}
dict_example.clear()
print("After clear:", dict_example)
2. copy() - Returns a shallow copy of the dictionary.
Example:
dict_example = {'a': 1, 'b': 2}
dict_copy = dict_example.copy()
print("Dictionary copy:", dict_copy)
3. get(key) - Returns the value for the given key if the key exists, else returns None (or a default
value if provided).
Example:
dict_example = {'a': 1, 'b': 2}
value = dict_example.get('a')
print("Value for key 'a':", value)
4. items() - Returns a view object that displays a list of tuple pairs (key, value).
Example:
dict_example = {'a': 1, 'b': 2}
items = dict_example.items()
print("Items:", items)
5. keys() - Returns a view object that displays a list of all the keys in the dictionary.
Example:
dict_example = {'a': 1, 'b': 2}
keys = dict_example.keys()
print("Keys:", keys)
6. pop(key) - Removes the item with the specified key and returns its value.
Example:
dict_example = {'a': 1, 'b': 2}
popped_item = dict_example.pop('a')
print("Popped item:", popped_item)
print("After pop:", dict_example)
7. popitem() - Removes and returns the last key-value pair as a tuple.
Example:
dict_example = {'a': 1, 'b': 2}
popped_item = dict_example.popitem()
print("Popped item:", popped_item)
print("After popitem:", dict_example)
8. setdefault(key, default) - Returns the value of the key if it exists, else inserts the key with the
default value and returns the default.
Example:
dict_example = {'a': 1, 'b': 2}
default_value = dict_example.setdefault('c', 3)
print("After setdefault:", dict_example)
9. update(dict2) - Updates the dictionary with the key-value pairs from another dictionary or iterable.
Example:
dict_example = {'a': 1, 'b': 2}
dict_example.update({'b': 3, 'c': 4})
print("After update:", dict_example)
10. values() - Returns a view object that displays a list of all the values in the dictionary.
Example:
dict_example = {'a': 1, 'b': 2}
values = dict_example.values()
print("Values:", values)
11. fromkeys(iterable, value=None) - Creates a new dictionary with keys from the iterable and
values set to the specified value.
Example:
keys = ['a', 'b', 'c']
new_dict = dict.fromkeys(keys, 0)
print("From keys:", new_dict)
12. del - Deletes an item from the dictionary by key.
Example:
dict_example = {'a': 1, 'b': 2}
del dict_example['b']
print("After del:", dict_example)
Note: Dictionaries are mutable, meaning that their values can be changed, added, or removed using
the methods mentioned above.