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
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
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
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
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.
The post Python dict setDefault appeared first on Java2Blog.