Articles → PYTHON → Setdefault Method Of Dictionary In Python
Setdefault Method Of Dictionary In Python
Scenario
car = {
"model": "Breeza",
"year": 2016
}
- If the key "brand" does not exist in the dictionary then add the key
- Returns the value of the key "brand"
car = {
"model": "Breeza",
"year": 2016
}
if any("brand" in d for d in car)== False:
car["brand"] = "Maruti"
print(car["brand"])
Setdefault Method In Action
car = {
"model": "Breeza",
"year": 2016
}
car.setdefault("Brand", "Maruti")
print(car["Brand"])
print(car)
Output