Python .setdefault()

StevenSwiniarski's avatar
Published May 23, 2022
Contribute to Docs

The .setdefault() method will return the value of a dictionary entry for a specified key. If the specified key does not exist in the dictionary, it will create an entry for it with the specified value.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

dictionary.setdefault(key, value)

Where key is the key of the value to return. If key does not exist in dictionary, it will be created. value is an optional parameter specifying the value for key if a new entry is created, it has no effect otherwise. If value is not specified, the value None will be used.

Codebyte Example

The following example creates a dictionary, then uses .setdefault() to return values from it:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours