Python Dictionary setdefault() Method

Last Updated : 5 Jan 2026

In Python, the setdefault() method is a dictionary method used to set default value to the key. It returns value, if the key is present. Otherwise it insert key with the default value. Default value for the key is None.

Syntax of the setdefault() Method in Python Dictionary

The following is the syntax of the dictionary setdefault() method:

Parameters

  • key: key to be searched.
  • default: This value to be returned, if the key is not found.

Return

It returns a value, if the key is present. Otherwise None or default value.

Examples of Dictionary setdefault()

We will now look at some examples of the dictionary setdefault() method.

Example 1: Working of the setdefault() Method

This example shows how the setdefault() method work in Python.

Example

Compile and Run

Output:

Given Dictionary: {'apple': 20, 'banana': 14, 'watermelon': 2, 'kiwi': 12, 'oranges': 24}
Updated Dictionary: {'apple': 20, 'banana': 14, 'watermelon': 2, 'kiwi': 12, 'oranges': 24, 'guava': 11}

Explanation:

In this example, we are given a dictionary consisting of some elements. We used the setdefault() method to set the default value of a key. Since the key does not exist in the dictionary, the item is added to the dictionary with a default value.

Example 2: If Key Exists in the Dictionary

Let us see an example showing what happens if the key already exists in the dictionary

Example

Compile and Run

Output:

Given Dictionary: {'apple': 20, 'banana': 14, 'watermelon': 2, 'kiwi': 12, 'oranges': 24}
Default Value of 'kiwi' 12
Updated Dictionary: {'apple': 20, 'banana': 14, 'watermelon': 2, 'kiwi': 12, 'oranges': 24}

Explanation:

In this example, we are given a dictionary consisting of some elements. We used the setdefault() method to set the default value of a key. Since the key already exist in the dictionary, it returns the value associated with it.

Example 3: If we don't provide Value to the Key

Let us see an example showing what happens if don't provide the value to the key.

Example

Compile and Run

Output:

Given Dictionary: {'apple': 20, 'banana': 14, 'watermelon': 2, 'kiwi': 12, 'oranges': 24}
Default Value of 'mango' None
Updated Dictionary: {'apple': 20, 'banana': 14, 'watermelon': 2, 'kiwi': 12, 'oranges': 24, 'mango': None}

Explanation:

In this example, we are given a dictionary consisting of some elements. We used the setdefault() method with the key. Since the key does not exist in the dictionary, the item is added to the dictionary without a default value i.e., None.

Conclusion

In Python, setdefault() is a dictionary method and a useful tool for setting the default value of a key if the user has not provided a value. It returns the value if the key is present. This method comes in handy as it avoids key errors and simplifies value assignment for new data entries. Python developers use this method where dynamic value assignment or safe retrieval is required with Dictionaries.