Python dictionary setdefault() method [With Examples]

In this article, we will explore one of the powerful features of the Python dictionary setdefault() method, which allows you to retrieve the value of a given key if it exists or set a default value if it does not.

In addition to this, we will also learn the syntax and usage of the setdefault() method, along with some practical examples to help you understand its applications.

Dictionary setdefault() method in Python

Below are the topics that we are doing to discuss in this article:

  • Introduction to Python Dictionary setdefault() method
  • Syntax of the setdefault() method
  • Purpose and use cases of the setdefault() method

Python Dictionary setdefault() method

The Python dictionary setdefault() method is a built-in method that allows you to retrieve the value associated with a given key in the Python dictionary or set a default value if the key is not found.

It is particularly useful when working with Python dictionaries where we want to initialize values for keys that may or may not be present.

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

dictionary.setdefault(key, default_value)

Parameters:

  • key: The key to be searched in the dictionary.
  • default_value (optional): The default value is to be returned if the key is not found in the dictionary. If not provided, the default value is None.

Return value:

The method returns the value associated with the key if it exists; otherwise, it returns the specified default value.

setdefault() method in Python Dictionary Examples

Let’s start with examples to demonstrate the usage of the setdefault() method:

Example#1 Basic Example of setdefault() Method

students = {'Alice': 21, 'Bob': 24, 'Charlie': 23}

age = students.setdefault('Alice', 22)
print(age)  

age = students.setdefault('David', 25)
print(age)  
print(students)

In this example, we have a Python dictionary called students containing names as keys and ages as values. When we call students.setdefault('Alice', 22), since ‘Alice’ is already in the Python dictionary, the method returns her age (21).

When we call students.setdefault('David', 25), since ‘David’ is not in the Python dictionary, the method adds the key-value pair (‘David’, 25) to the Python dictionary and returns the default value 25.

Output:

Python dictionary setdefault method
Python dictionary setdefault method

Example#2 Practical Usage of setdefault() Method

sentence = "New York is a great city with a great skyline"
word_count = {}

for word in sentence.split():
    word_count.setdefault(word.lower(), 0)
    word_count[word.lower()] += 1

print(word_count)

In this example, we have a string sentence containing a sentence about New York City, and an empty Python dictionary word_count.

We iterate through each word in the sentence, and for each word, we use the setdefault() method to initialize its count to 0 if it’s not already in the Python dictionary. Then, we increment the count of that word by 1.

Output:

Python dictionary setdefault method example
Python dictionary setdefault method example

Example#3 Comparison with dict.get()

students = {'John': 28, 'Emily': 23, 'Michael': 25}

age = students.get('Lucas', 30)
print(age)  
print(students)

In this example, the dict.get() method returns the default value (30) for the key ‘Lucas’ since it is not in the Python dictionary. However, unlike the setdefault() method, it does not add the key-value pair (‘Lucas’, 30) to the Python dictionary.

Output:

Dictionary setdefault method in Python
Dictionary setdefault method in Python

Conclusion

In this article, we explored the Python dictionary setdefault() method, its syntax, basic usage, and practical applications. We also compared it with the dict.get() method, highlighting the key differences between the two.

The setdefault() method is a useful tool for initializing values in a dictionary when dealing with keys that may or may not be present, making it a valuable addition to your Python toolkit.

You may also like to read the following articles: