setdefault() method in Python Dictionary

Published: July 07, 2022

setdefault() method in Python Dictionary

setdefault() method is one of the most interesting method in Python Dictionary. It returns with the value of an associated key. If the key isn't there then, we can have default value as None. Or, in case we don't want the default value - None then, we can have one of our own choice. We will cover each of these with suitable example in following section.

The syntax for setdefault() method in Python Dictionary is -

dictionary_name.setdefault(key_name, value)

where, value is an optional parameter. Default value is None. If the key doesn't exist then, either it sets the default value to None or the one we specified.

key_name - name of the key whose value we want retrieve.

We cover what we have discussed till now with relevant examples next.

setdefault() method in Python Dictionary

Let’s say we have dictionary, x –

x = {"name":"abc", "age":24, "address":"xyz, qwerty"}

Example I. First, we start with how to get the value of an associated key. No complications here. The key is available, the value is there as well.

y = x.setdefault("address")
Next, use print() method -

It would return with -

xyz, qwerty

As already mentioned, the value of the associated key is already available. So, it acts accordingly.

Example II. In this example, we would consider a key_name which won't be there in our dictionary. And, we don't provide a value. In that scenario, it would show us default value - None. Continuing with the same dictionary, x -

y = x.setdefault("key_not_there")

The outcome in this case would be -


As key --> key_not_there isn't there in the dictionary. Therefore, it would shift to default value - None.

Example III. If the key is already there with a value. Then, if we try to set a new value using setdefault() method - it won't work.

y = x.setdefault("name", "xyz")

It would still return with the initial value (and, not the value - xyz)


Example IV. Lastly, if the key itself isn't available and we want a value of our own choice instead of None. Then,

y = x.setdefault("key_not_there", "value_y")

This would return with -


The above outcome is self-explanatory. The default value None is replaced with the value we provided - value_y.

In conclusion, we have discussed setdefault() method in Python Dictionary.