Python Dict setdefault():

The setdefault() method returns the value of the given key from the dictionary. However, it adds a new key with a given default value in the absence of key.

Method signature

The signature for the setdefault() method is as shown below. Here, d refers to the dictionary, and v stores the return value.

v=d.setdefault(k, defaultvalue)

Method parameters and return type

  • The setdefault() takes key and default value as a parameter. Here, k specifies a key to search for whereas the default value is optional. In the absence of a key, k and the default value is added in the dictionary as a new key-value pair. Furthermore, in absence of a default value, None is inserted.
  • However, it returns the value of a key specified. But in absence of a key, it returns default value or None.

Python Dictionary setdefault Examples:

Example 1: Let us take a dictionary d, mapping decimal numbers to country names. Furthermore, v is used here to store the value of the key. Since the dictionary contains key “India”, its default value will be set as “Delhi”. However, key “France” is not present, so this key will be inserted along with the specified default value.

d={"India":"Delhi", "Switzerland":"Bern","Germany":"Berlin"}
#Using setdefault and printing
print("Value is ",v) 
print("Value is ",v) 
print("Dictionary d is ",d)


Value is  Delhi
Value is  Paris
Dictionary d is  {'India': 'Delhi', 'Switzerland': 'Bern', 'Germany': 'Berlin', 'France': 'Paris'}

Example 2:

In this example, let us take a dictionary d, mapping numbers to a city name. Here, we will call this method with key 2 that is already present in the dictionary. As we can see, it will extract the value of the given key. After that, we will call a method with key 4 and no default value. As a result, key-value pair 4 and None is inserted in the dictionary.

# Using setdefault method and printing
print("Value is ",v) 
print("Dictionary is", d)


Value is  Chennai
Dictionary is {1: 'Delhi', 2: 'Chennai', 3: 'Hyderabad', 4: None}

Example 3:

In this example, We will take a dictionary mapping decimal numbers to alphabets. Here, we will use a while loop that iterates 6 times on a dictionary. As a result, it prints all the values for the keys present in the dictionary and adds two keys, 5 and 6, with the default value “Python” in it.

# Using setdefault method and printing
while i < 7 :
	print("Value for ",i," is",t)
#Printing dictionary
print("Dictionary is ",d)


Value for  1  is A
Value for  2  is B
Value for  3  is C
Value for  4  is D
Value for  5  is Python
Value for  6  is Python
Dictionary is  {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'Python', 6: 'Python'}


The setdefault() method returns a value of key in the presence of the key. However, if the key is not present, it inserts it with the default value. In the absence of the default value parameter, it inserts None.


Happy Learning 🙂

Leave A Comment