Python dictionary setdefault() method
In this tutorial, we are going to learn setdefault() method in Python with some easy examples. That is most important to many programmers while dealing with a dictionary.
Usually, in Python, while dealing with the “Dictionary” datatype sometimes we require to find whether an element is present in a dictionary or not.
To solve this problem we use a method in Python called “setdefault()” method.
Python setdefault() method
Before starting, first of all, let us know about a dictionary in Python.
Dictionary in Python: A dictionary is a collection datatype that contains elements, usually stored in the form of keys and values. The elements in a dictionary are unordered, unchangeable and indexed.
Representation:
We usually represent a dictionary in Python by using “{}” brackets.
Note:
In the dictionary, values are stored in “key: value” pairs.
setdefault() method:
Syntax:
setdefault(key,value)
Parameters:
key: The element that we want to search in the dictionary.
value: The value that is to be inserted in the dictionary if the key is not found.
Note:
When the value is not specified then by default it assigns to “None”.
Calling:
Because setdefault() is a method, therefore, we use the dot operator “.” to call the setdefault() method.
Return:
The setdefault() method returns THE VALUE OF THE KEY IF IT IS PRESENT IN THE DICTIONARY, else it INSERTS KEY WITH THE SPECIFIED VALUE INTO THE DICTIONARY.
EXAMPLE 1:
#Python code to demonstrate setdefault() method >>> dict = {"a" : "code","b" : "speedy","c" : "software","d" : "solutions"} >>> print(dict) >>> dict.setdefault("c")
OUTPUT:
{'a': 'code', 'b': 'speedy', 'c': 'software', 'd': 'solutions'} 'software'
In the above example by calling the setdefault() method we get the value of key i.e ‘software’.
EXAMPLE 2:
#Python code to demonstrate setdefault() method >>> dict = {"a" : "code","b" : "speedy","c" : "software","d" : "solutions"} >>> print(dict) >>> dict.setdefault("e") >>> print(dict)
OUTPUT:
{'a': 'code', 'b': 'speedy', 'c': 'software', 'd': 'solutions'} {'a': 'code', 'b': 'speedy', 'c': 'software', 'd': 'solutions', 'e': None}
In the above example, because the key is not present in the dictionary therefore setdefault() method returns “none”.
EXAMPLE 3:
#Python code to demonstrate setdefault() method >>> dict = {"a" : "code","b" : "speedy","c" : "software","d" : "solutions"} >>>print(dict) >>> dict.setdefault("f","company") >>> print(dict)
OUTPUT:
{'a': 'code', 'b': 'speedy', 'c': 'software', 'd': 'solutions'} {'a': 'code', 'b': 'speedy', 'c': 'software', 'd': 'solutions', 'e': None, 'f': 'company'} In the above example because the key "f" isn't present in the dictionary setdefault() method, therefore, inserts the value "company" into the dictionary.
Finally, I hope that this tutorial was helpful to understand the setdefault() method successfully!!
Also read:
Leave a Reply