Table of Contents
In this tutorial, we will see about Python dict setDefault method.
Python dictionary setDefault method is used to return the value if present in dictionary else inserts the key with value in dictionary if default value is provided.
Syntax
1 2 3 |
dict.setdefault(key[, default_value]) |
Return
It returns the value if key exists in dictionary else it inserts key with value.
Python dictionary setDefault example
Example 1: If key is present in dictionary
1 2 3 4 5 6 7 8 |
listOfCountries={"India":"Delhi","China":"Beijing","Australia":"Canberra","UK":"London"} #If key is present in dictionary capital=listOfCountries.setdefault("China") print("Capital of china:",capital) |
Output:
Capital of china: Beijing
Example 2: If key is present in dictionary but default value is not provided
1 2 3 4 5 6 7 8 |
listOfCountries={"India":"Delhi","China":"Beijing","Australia":"Canberra","UK":"London"} #If key is not present in dictionary and default is not provided capital=listOfCountries.setdefault("USA") print("Capital of USA:",capital) |
Output:
Capital of USA: None
Example 2: If key is present in dictionary and default value is provided
1 2 3 4 5 6 7 8 |
listOfCountries={"India":"Delhi","China":"Beijing","Australia":"Canberra","UK":"London"} #If key is not present in dictionary and default is provided capital=listOfCountries.setdefault("USA","washigton") print("Capital of USA:",capital) |
Output:
Capital of USA: washigton
That’s all about Python dict setDefault method.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.