Skip to content
Home » Dictionary Methods – setdefault

Dictionary Methods – setdefault

Spread the love

In some of my previous articles we discussed the following dictionary methods:

pop and popitem

get

Feel free to read about them if you haven’t done so yet.

In this article we’ll be talking about the setdefault method, which is similar to get.

Here’s the video version of the article:

The method setdefault(key, default = None) works like get, but if key is not in the dictionary, it is created and set to default. Here’s our dictionary:

>>> personal_data = {"name" : "Adam", "age" : 10}

To illustrate the difference between the two methods, let’s use them one by one.

get

Let’s start with the get method:

>>> personal_data = {"name" : "Adam", "age" : 10}
>>> personal_data.get("age", 18)
10

So, we set the key “age” to the default value 18. But it turns out it’s still 10. This is because this key already exists in the dictionary and the default values are set only to newly added keys.

So, let’s use the get method with a key that doesn’t yet exist:

>>> personal_data.get("city", "Unknown")
'Unknown'

As you can see, we got the default value of “Unknown”, but the element was not added to the dictionary:

>>> personal_data
{'name': 'Adam', 'age': 10}

setdefault

And now let’s see how the setdefault method works. There is no difference if the key already exists in the dictionary:

>>> personal_data.setdefault("age", 18)
10
>>> personal_data
{'name': 'Adam', 'age': 10}

But there’s a difference if it doesn’t. As the key “city” doesn’t exist in the dictionary, it’s created and its value is set to default:

>>> personal_data.setdefault("city", "Unknown")
'Unknown'

If we now print the dictionary, we can see that the new key-value pair has been added:

>>> personal_data
{'name': 'Adam', 'age': 10, 'city': 'Unknown'}

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply