Learn Before
Concept
setdefault(key[, default])
The setdefault() method returns the value of a specified key. If the key does not exist, the key is inserted with the default value parameter. Usage:
student = { "name": "John", "year": 2, "grade": 95 } student_name = student.setdefault("name", "Joe") print(student_name) student_age = student.setdefault("age", 19) print(student_age)
The first print statement outputs John, as the key "name" already exists. The second print statement outputs 19, as there is no "age" key in the Dictionary. Additionally, the key-value pair {"age": 19} is added to the student Dictionary.
0
1
Updated 2021-05-22
Tags
Python Programming Language
Data Science