Home »
Python
Python Dictionary setdefault() Method (with Examples)
Python Dictionary setdefault() Method: In this tutorial, we will learn about the setdefault() method of a dictionary with its usage, syntax, parameters, return type, and examples.
By IncludeHelp Last updated : June 12, 2023
Python Dictionary setdefault() Method
The setdefault() is an inbuilt method of dict class that is used to get the value of an item with the specified key and it sets an item (key, value) if the specified key does not exist in the dictionary. The method is called with this dictionary and returns the value of the specified key.
Syntax
The following is the syntax of setdefault() method:
dictionary_name.setdefault(key, value)
Parameter(s):
The following are the parameter(s):
- key – It specifies the key name whose value to be returned to set.
- value – It is an optional parameter, its default value is None, if the key does not exist, value becomes the value of the specified key.
Return Value
The return type of this method is the type of the value, it returns the value of specified keys.
Note: If value is not defined, it returns None.
Example 1: Use of Dictionary setdefault() Method
alphabets = {
"a": "Apple",
"b": "Bat",
"c": "Cat"
}
result = alphabets.setdefault("d", "Dog")
print(result)
Output
Dog
Example 2: Use of Dictionary setdefault() Method
# dictionary declaration
student = {
"roll_no": 101,
"name": "Shivang",
"course": "B.Tech"
}
# printing dictionary
print("data of student dictionary...")
print(student)
# getting value of 'roll_no'
x = student.setdefault("roll_no", 0)
print("roll_no:", x)
# getting value of address key
# that does not exist, then function
# inserts given key & value
x = student.setdefault("address", "New Delhi")
print("address:", x)
# printing dictionary
print("data of student dictionary after setdefault()...")
print(student)
# getting value of age key
# that does not exist, then function
# inserts given key & None
x = student.setdefault("age")
print("age:", x)
# printing dictionary
print("data of student dictionary after setdefault()...")
print(student)
Output
data of student dictionary...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech'}
roll_no: 101
address: New Delhi
data of student dictionary after setdefault()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'address': 'New Delhi'}
age: None
data of student dictionary after setdefault()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'address': 'New Delhi', 'age': None}