Python dict setDefault

Previous
Next

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

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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog