Python dict setDefault

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.