Python Dictionary setdefault() method
Python Dictionary setdefault() method
The dictionary.setdefault () method in Python returns the value of the item with the specified key.
Syntax
dictionary.setdefault(keyname, value)
Parameter
keyname- This parameter represents the keyname of the item you want to return the value.
value(optional)- This parameter represents a Key with a value default_value is inserted to the dictionary. If no value is provided, the default_value will be none.
Return
This method returns an arbitrary element (key, value) pair from the given dictionary.
Example 1
# Python program explaining
# the dictionary.setdefault() method
# initialising the dictionary
fruits = {
"banana" : "vitamins",
"orange": "citric acid",
"grapes": 5
}
# printing the Dictionary
print("Dictionary:",fruits)
# returning the value of the key.
defaultValue=fruits.setdefault("grapes","vitamin c")
print("Value of the key: \n", defaultValue)
Output
Dictionary: {'grapes': 5, 'orange': 'citric acid', 'banana': 'vitamins'}
Value of the key: 5
Example 2
# Python program explaining
# the dictionary.setdefault() method
# initializing the dictionary
student = {'studentName': 'Reema','Roll No':'15cs1029'}
# The given key is not in the dictionary
branch = student.setdefault('branch')
print('Student Details = ',student)
print('Branch = ',branch)
# The specified key is not in the dictionary
# default_value is provided
age = student.setdefault('age', 22)
print('Student Details = ',student)
print('age = ',age)
Output
Student Name = {'Roll No': '15cs1029', 'branch': None, 'studentName': 'Reema'}
Branch = None
Student Name = {'Roll No': '15cs1029', 'age': 22, 'branch': None, 'studentName': 'Reema'}
age = 22
