In this Python tutorial, you will learn what setdefault() method of dictionary dict class does, its syntax, and how to use this method to set a default value for a key if the given key is not present in the dictionary, with example programs.
Python Dictionary setdefault()
Python Dictionary setdefault(key[, default]) method returns the value for the key if the key is present.
If the key is not present in the dictionary, (key, default) pair is inserted to the dictionary and the default value is returned. In this scenario, if default value is not provided, None is taken as the default value.
In this tutorial, we will learn the syntax of dict.setdefault() method and go through examples covering different scenarios for the arguments that we pass to setdefault() method.
Syntax
The syntax of dict.setdefault() is
dict.setdefault(key[, default])
where
key is the key we want to lookup in the dictionary.
default is the value we want setdefault() to return and insert to dictionary when there no match for the key in dictionary. default value is optional, and the default value for default is None.
Examples (3)
1. Get value from a dictionary by key
In this example, we will get the value for key 'b'
in the dictionary. The key 'b'
is present in the dictionary. No default value will be given as second argument.
Python Program
myDictionary = {'a': 58, 'b': 22, 'c': 39}
value = myDictionary.setdefault('b')
print(value)
Program Output
61
As the key is present in the dictionary, setdefault() method returned the corresponding value.
2. Set a default value for a key in dictionary, and return the value
In this example, we will get the value for key 'm'
in the dictionary. The key 'm
is not present in the dictionary. Default value of 0
is given as second argument.
Python Program
myDictionary = {'a': 58, 'b': 22, 'c': 39}
value = myDictionary.setdefault('m', 0)
print(value)
print(myDictionary)
Program Output
0
{'a': 58, 'b': 22, 'c': 39, 'm': 0}
As the key is not present in the dictionary, and default value is given to the method, setdefault() returns the default value and inserts 'm':0
to the dictionary.
3. Get a value for a key in dictionary using setdefault() but no default value given
In this example, we will call setdefault() method with key 'm'
on the dictionary. The key 'm'
is not present in the dictionary. No default value will be given as second argument.
Python Program
myDictionary = {'a': 58, 'b': 22, 'c': 39}
value = myDictionary.setdefault('m')
print(value)
print(myDictionary)
Program Output
None
{'a': 58, 'b': 22, 'c': 39, 'm': None}
As the key is not present in the dictionary and no default value is provided to setdefault() method, the method returns None and insert the item 'm': None
to the dictionary.
Conclusion
In this Python Tutorial, we learned about Python Dictionary method dict.setdefault().