How to Use the Dictionary setdefault() Method in Python

09/18/2021

Contents

In this article, you will learn how to use the Dictionary setdefault() method in Python.

Dictionary setdefault() Method

The setdefault() method in Python is a built-in dictionary method that allows you to insert a new key-value pair into a dictionary if the key does not already exist, and return the value associated with that key. If the key already exists in the dictionary, it returns the value associated with the key without changing the dictionary.

Syntax

The syntax for the setdefault() method is as follows:

dictionary.setdefault(key, default_value)
Parameters
  • key: The key you want to search for in the dictionary.
  • default_value: The value to be inserted if the key is not already present in the dictionary.
Example

Here is an example of how to use the setdefault() method in Python:

# Create a dictionary
my_dict = {'apple': 2, 'orange': 3, 'banana': 4}

# Try to access a key that does not exist
grapes_count = my_dict.setdefault('grapes', 0)
print(grapes_count) # Output: 0

# The dictionary has now been updated with the new key-value pair
print(my_dict) # Output: {'apple': 2, 'orange': 3, 'banana': 4, 'grapes': 0}

# Try to access a key that already exists in the dictionary
apple_count = my_dict.setdefault('apple', 5)
print(apple_count) # Output: 2 (the value associated with the existing 'apple' key)

# The dictionary remains unchanged
print(my_dict) # Output: {'apple': 2, 'orange': 3, 'banana': 4, 'grapes': 0}

In the above example, we first create a dictionary with some key-value pairs. We then use the setdefault() method to try and access a key that does not exist in the dictionary (‘grapes’). Since the key does not exist, the method inserts the new key-value pair (‘grapes’: 0) into the dictionary and returns the default value 0. We print the value returned by the setdefault() method to verify that it is indeed 0, and also print the updated dictionary to see the new key-value pair.

Next, we use the setdefault() method to try and access a key that already exists in the dictionary (‘apple’). Since the key already exists, the method simply returns the value associated with the key (2). We print the value returned by the setdefault() method to verify that it is indeed 2, and also print the dictionary to confirm that it remains unchanged.