Home »
Python
Python Dictionary setdefault() Method with Example
Python Dictionary setdefault() Method: Here, we are going to learn to get the value of an item with specified key and if key does not exist then set the key and value?
Submitted by IncludeHelp, on November 26, 2019
Dictionary setdefault() Method
setdefault() method 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.
Syntax:
dictionary_name.setdefault(key, value)
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:
# Python Dictionary setdefault() Method with Example
# dictionary declaration
student = {
"roll_no": 101,
"name": "Shivang",
"course": "B.Tech",
"perc" : 98.5
}
# 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', 'perc': 98.5}
roll_no: 101
address: New Delhi
data of student dictionary after setdefault()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'address': 'New Delhi'}
age: None
data of student dictionary after setdefault()...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'address': 'New Delhi', 'age': None}
ADVERTISEMENT
ADVERTISEMENT