Articles → PYTHON → Setdefault Method Of Dictionary In Python

Setdefault Method Of Dictionary In Python






Scenario




car = {  
  "model": "Breeza",
  "year": 2016
}


  1. If the key "brand" does not exist in the dictionary then add the key.
  2. 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


Picture showing the output of setdefault method of dictionary in python
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Friday, October 15, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250