PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Python · Theory

dict.setdefault()

← All stacks

Theory

258/268

dict.setdefault()

dict.setdefault() works on a dictionary — labelled data like marks["Asha"] = 90. Keys map to values. Loop with .items() when you need both.

dict.setdefault() — output — 90, then 0, then {'Asha': 90, 'Neha': 0}. setdefault adds only if missing.

Trap for dict.setdefault() — writing d[missing] in a viva. Prefer get when the key might not exist.

Diagram
{ "Asha": 90, "Ravi": 85 }
         │           │
        key        value
Exam tip

get vs [] — one sentence + tiny dict of marks.

Example

# dict.setdefault()
d = {"Asha": 90}
print(d.setdefault("Asha", 0))
print(d.setdefault("Neha", 0))
print(d)

dict.setdefault() — output: 90, then 0, then {'Asha': 90, 'Neha': 0}. setdefault adds only if missing.

Short notes

  • Defdict.setdefault() works on a dictionary.
  • Ruledict.setdefault() — get when key may miss.
  • Rememberdict.setdefault() — items() → key and value.
  • Trapdict.setdefault() — d[missing] → KeyError.

Questions

1

Explain dict.setdefault() as if you are teaching a junior — definition, then one tiny script.

2

What does the example print, and why?

3

What mistake do freshers make with dict.setdefault()?

Previous← dict.values()Nextdict.clear() →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.