In some of my previous articles we discussed the following dictionary methods:
– 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'}