In this article, we’ll learn what Python dictionary setDefault method is and how to properly use it.
To better understand how Python dictionary setDefault method works, multiple Python code examples will be provided with detailed with step by step explanation.
After reading this post, you’ll have a detailed knowledge of how to use Python dictionary setDefault method practically.
What is Python Dictionary SetDefault?
It is a method of Python dictionary which is used to return a value assigned to a key in dictionary. If the specified key is not present then this method add the key to the dictionary which is passed to it as an argument.
By using this method, we can assign a value to key(which passed to this method).
Let’s first understand its syntax, then we’ll practically implement it using proper Python code examples.
Syntax of SetDefault Method
dictName.setdefault( key, value(optional) )
As you can see, we have a set default method having two parameters. First one is key that will be searched across the dictionary. Second parameter is optional. If the key is not found then this method will return none. But if you specify some data like string, int etc. in that second argument of set default method then it will be returned if the key is not found.
Implementing Python Dictionary SetDefault Method (Multiple Examples)
Below examples will practically demonstrate usage of this setdefault() method.
Example 1: Fetch Data From Dictionary
dictValues={'name':'Yasir','age':25,'height':6} print( dictValues.setdefault('age') )
Output
25
Value of the specified key is returned by our set default method.
Example 2: setdefault() Method Returns None
dictValues={'name':'Yasir','age':25,'height':6} print( dictValues.setdefault('weight') ) // none print(dictValues) // new key value pair added
Output
None {'name': 'Yasir', 'age': 25, 'height': 6, 'weight': None}
The specified key is not found in this dictionary so this method returns None. We can also see that a new key value pair is added with the same specified key and a None value assigned to it.
Example 3: Return Default Value if Key not Found
If you want to return some specific value in case the key is not found then see below code:
dictValues={'name':'Yasir','age':25,'height':6} print(dictValues.setdefault('weight',80)) print(dictValues)
Output
80 {'name': 'Yasir', 'age': 25, 'height': 6, 'weight': 80}
As you can see that the default value(second argument passed to setdefault() method) is assigned to the newly added key in dictionary.
So this is how you can easily use Python dictionary setdefault method in your own Python code as well.
Don’t hesitate to ask if you still have questions related to the implementation of Python dictionary setdefault method. I’ll be very glad to answer all.
Conclusion
To conclude, now you have an in-depth practical understanding of how to properly use Python dictionary setdefault method. I’d be looking forward to have your valuable feedback on this post. Thank you for reading it.