Dictionary is one of the Python built-in data types that act as the container for key-value pairs. It is also called ‘associative memories’ or ‘associative arrays’ in other programming languages.
Python dictionaries are indexed by keys, and it is mutable in nature. Except its keys are immutable types and values can support either mutable or immutable types.
There are 11 dictionary methods available which we can use in the dictionary object.
Print all the dictionary methods
To check all the methods available in the dictionary, use list comprehension as:
# list comprehension to print # all the dictionary methods dict_methods = [method for method in dir(dict) if not method.startswith("__")]
Output:
['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
Consider a variable named my_dict containing three key: value
pairs initially. We will perform all the dictionary methods in that variable.
# dictionary object containing three # key: value pairs initially my_dict = {'C': 'Dennis Ritchie ', 'C++': 'Bjarne Stroustrup', 'Python': 'Guido van Rossum', 'Java': 'James Gosling'}
Note: variable is the reference to an object. Right now my_dict is the dictionary type object.
1. clear( )
It removes all the items from the dictionary.
# clear all the items # inside my_dict my_dict.clear() print(my_dict)
Output:
{}
2. copy( )
It is used to copy dictionary items into a new dictionary object.
# copy my_dict items into my_2nd_dict my_2nd_dict = my_dict.copy() print(my_2nd_dict)
Output:
{'C': 'Dennis Ritchie ', 'C++': 'Bjarne Stroustrup', 'Python': 'Guido van Rossum', 'Java': 'James Gosling'}
3. fromkeys(iterable, value=None)
This method is used to create a dictionary from iterable with the default value: None if not pass as an argument.
Iterable objects can be lists, sets, tuples, strings, dictionaries, etc. But as keys are immutable in nature only tuple, string data types are used.
# tuple items as keys dict_keys = ("C", "C++", "Python", "Java") # create my_dict from fromkeys() methods # with default value: None my_dict = dict.fromkeys(dict_keys) print("All keys value set to None") print(my_dict) # contains all values as None # with value: Programmer my_dict = dict.fromkeys(dict_keys, "Programmer") print("All keys value set to Programmer") print(my_dict) # contains all values as Programmer
Output:
All keys value set to None {'C': None, 'C++': None, 'Python': None, 'Java': None} All keys value set to Programmer {'C': 'Programmer', 'C++': 'Programmer', 'Python': 'Programmer', 'Java': 'Programmer'}
4. get(key_name, default=None)
It is used to get the value of the key pass as an argument. It returns the default value: None if the specified key is not present in the dictionary.
# using get() method to get value # of Python python_value = my_dict.get("Python") print(python_value) # get the value of Swift # which not exist swift_value = my_dict.get("Swift") print(swift_value) # return None
Output:
Guido van Rossum None
Change the default value
You can change the default value from None to any name that is suitable according to your needs.
# change get() default value swift_value = my_dict.get("Swift", "Not exist") print(swift_value)
Output:
Not exist
5. items( )
It returns the view object that contains the dictionary’s key: value
pairs in list format.
# use items() method in my_dict my_dict_items = my_dict.items() print(my_dict_items)
Output:
dict_items([('C', 'Dennis Ritchie '), ('C++', 'Bjarne Stroustrup'), ('Python', 'Guido van Rossum'), ('Java', 'James Gosling')])
6. values( )
It returns the view object that contains all the values in the list format.
# use values() method in my_dict my_dict_values = my_dict.values() print(my_dict_values)
Output:
dict_values(['Dennis Ritchie ', 'Bjarne Stroustrup', 'Guido van Rossum', 'James Gosling'])
7. keys( )
It returns the view object that contains all the keys in the list format.
# use keys() method in my_dict my_dict_keys = my_dict.keys() print(my_dict_keys)
Output:
dict_keys(['C', 'C++', 'Python', 'Java'])
8. pop(key)
It removes and returns the value of the specified key pass as an argument.
# use pop() to remove Python # and return its value remove_python = my_dict.pop("Python") print(remove_python) # check if Python remove print(my_dict)
Output:
Guido van Rossum {'C': 'Dennis Ritchie ', 'C++': 'Bjarne Stroustrup', 'Java': 'James Gosling'}
It raised the KeyError
exception if the specified key is not found.
# if unknown key pass in pop() print(my_dict.pop("Swift"))
Output:
Traceback (most recent call last): File "/home/dict_methods.py", line 28, in <module> print(my_dict.pop("Swift")) KeyError: 'Swift'
9. popitem( )
It works similar to the pop() method in the sense that it only removes the last inserted item into the dictionary object. Here pairs are returned in the LIFO order.
my_dict object key: value
inserted order:
C ⇒ C++ ⇒ Python ⇒ Java
So popitem() method, remove and return a tuple of key-value pair from the dictionary as it was inserted last.
# popitem() remove last item inserted last_item = my_dict.popitem() print("Last item ->", last_item) print("my_dict updated as Java removed") print(my_dict) # remove last item on new object last_item = my_dict.popitem() print("Last item ->", last_item) print("my_dict updated as Python removed") print(my_dict)
Output:
Last item -> ('Java', 'James Gosling') my_dict updated as Java removed {'C': 'Dennis Ritchie ', 'C++': 'Bjarne Stroustrup', 'Python': 'Guido van Rossum'} Last item -> ('Python', 'Guido van Rossum') my_dict updated as Python removed {'C': 'Dennis Ritchie ', 'C++': 'Bjarne Stroustrup'}
It raised the KeyError
exception if the dict object is empty.
my_dict = {} #empty dict object print(my_dict.popitem())
Output:
Traceback (most recent call last): File "/home/dict_methods.py", line 20, in <module> print(my_dict.popitem()) KeyError: 'popitem(): dictionary is empty'
10. setdefault(key, default=None)
It is used to insert a key with the value if the key is not in the dictionary.
By default, the value is None if we do not pass any value.
# add new key JavaScript with value my_dict.setdefault("JavaScript", "Brendan Eich") # add new key Kotlin without value my_dict.setdefault("Kotlin") # new key: value are added print(my_dict)
Output:
{'C': 'Dennis Ritchie ', 'C++': 'Bjarne Stroustrup', 'Python': 'Guido van Rossum', 'Java': 'James Gosling', 'JavaScript': 'Brendan Eich', 'Kotlin': None}
But if the key we pass already exists, then this method returns the value of the key.
# update the existing key Python # return its first inserted value print(my_dict.setdefault("Python", "Programmer"))
Output:
Guido van Rossum
11. update(iterable)
It is used to update the dictionary items with the iterable dictionary object. If the key to be updated is not in the dictionary then it creates new pair. Otherwise, it updates the existing one.
# create new dict object to pass # as iterable new_dict = {'C': 'Sir Dennis', 'Python': 'Van Rossum'} # use update() to update values in my_dict my_dict.update(new_dict) print("Update the value with keys already existed") print(my_dict)
Output:
Update the value with keys already existed {'C': 'Sir Dennis', 'C++': 'Bjarne Stroustrup', 'Python': 'Van Rossum', 'Java': 'James Gosling'}
Passing new key: value as iterable
# create new dict object to pass # as iterable new_dict = {'JavaScript': 'Brendan Eich', 'Swift': 'Apple Developers', 'Python': 'Developer'} # use update() to update values in my_dict my_dict.update(new_dict) print("Update the value with key already existed and add new pair if not present") print(my_dict)
Output:
Update the value with key already existed and add new pair if not present {'C': 'Dennis Ritchie ', 'C++': 'Bjarne Stroustrup', 'Python': 'Developer', 'Java': 'James Gosling', 'JavaScript': 'Brendan Eich', 'Swift': 'Apple Developers'}