C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python Dictionary setdefault() MethodPython setdefault() method is used to set default value to the key. It returns value, if the key is present. Otherwise it insert key with the default value. Default value for the key is None. Signature of this method is given below. Signature
setdefault(key[, default]) Parameters
key: key to be searched. default: This value to be returned, if the key is not found. Return
It returns a value, if the key is present. Otherwise None or default value. Let's see some examples of setdefault() method to understand it's functionality. Python Dictionary setdefault() Method Example 1A simple example, if key is present, it returns associated value.
# Python dictionary setdefault() Method
# Creating a dictionary
coursefee = {'B,Tech': 400000, 'BA':2500, 'B.COM':50000}
# Displaying result
p = coursefee.setdefault('BA') # Returns it's value
print("default",p)
print(coursefee)
Output: default 2500
{'B,Tech': 400000, 'BA': 2500, 'B.COM': 50000}
Python Dictionary setdefault() Method Example 2If neither key nor default value is present, it returns None. See the following example.
# Python dictionary setdefault() Method
# Creating a dictionary
coursefee = {'B,Tech': 400000, 'BA':2500, 'B.COM':50000}
# Displaying result
p = coursefee.setdefault('BCA') # Returns it's value
print("default",p)
print(coursefee)
Output: default None
{'B,Tech': 400000, 'BA': 2500, 'B.COM': 50000, 'BCA': None}
Python Dictionary setdefault() Method Example 3If key is not present but default value is set, it returns default value. See an example.
# Python dictionary setdefault() Method
# Creating a dictionary
coursefee = {'B,Tech': 400000, 'BA':2500, 'B.COM':50000}
# Calling function
p = coursefee.setdefault('BCA',100000) # Returns it's value
# Displaying result
print("default",p)
print(coursefee)
Output: default 100000
{'B,Tech': 400000, 'BA': 2500, 'B.COM': 50000, 'BCA': 100000}
Next TopicPython Dictionary
|