1. Home
  2. Data Science
  3. Python
  4. What does setdefault(key, default) do in Python?

Added 25 Nov 2026

What does setdefault(key, default) do in Python?

  1. Always overwrites the key
  2. Returns the value if key exists, otherwise inserts default and returns it Correct answer
  3. Deletes the key
  4. Raises KeyError if missing

Correct answer

B. Returns the value if key exists, otherwise inserts default and returns it

5 views

MCQSEXAM

Explanation

setdefault inserts the key with default only when it is absent.

Reference

Asked in: Python Interview Dictionaries

https://docs.python.org/3/tutorial/datastructures.html#dictionaries

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More Python MCQs

Practise all Python MCQs

Similar MCQs