Python Dictionary setdefault()
In Python dictionary, setdefault() method returns the value of the given key, if the key is present in the dictionary and if not present it will inserts a key with a value to the dictionary.
Python Dictionary setdefault()
The syntax of setdefault() is:
1
dictionary.setdefault(key, default_value)
setdefault() Parameters
The python setdefault() method takes two parameters as arguments:
- key - Key to being searched in the dictionary.
- default_value - The value to be returned in case the key is not found. If not provided, the defalut_value will be None.
Let see some examples of python dictionaries setdefault() method.
Example 1: How to use setdefault() method on python dictionary?
1
2
3
4
5
Dogs = {'name' : 'Coco', 'age' : 4}
dog_age = Dogs.setdefault('age')
print('Age of Dog is:', dog_age)
Output:
1
2
Age of Dog is: 4
Example 2: How setdefault() works when a key is not in the dictionary?
1
2
3
4
5
6
7
8
9
10
11
12
13
Dogs = {'name': 'Coco'}
# key is not in the dictionary
color = Dogs.setdefault('color')
print('Dogs = ',Dogs)
print('color = ',color)
# key is not in the dictionary
# default_value is provided
age = Dogs.setdefault('age', 4)
print('Dogs = ',Dogs)
print('age = ',age)
Output:
1
2
3
4
5
Dogs = {'name': 'Coco', 'color': None}
color = None
Dogs = {'name': 'Coco', 'color': None, 'age': 4}
age = 4
Rules of setdefault()
- Only returns a result if the given key is present in the dictionary.
- Will return None when the key is not present in the dictionary and default value is not specified.
This post is licensed under CC BY 4.0 by the author.