Python Dictionary setdefault() MethodLast 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 DictionaryThe following is the syntax of the dictionary setdefault() method: Parameters
ReturnIt 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() MethodThis example shows how the setdefault() method work in Python. ExampleCompile and RunOutput:
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 DictionaryLet us see an example showing what happens if the key already exists in the dictionary ExampleCompile and RunOutput:
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 KeyLet us see an example showing what happens if don't provide the value to the key. ExampleCompile and RunOutput:
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. ConclusionIn 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. Next TopicPython-dictionary-clear-method |
We request you to subscribe our newsletter for upcoming updates.