Python

Python Menu

Python

Python Dictionary setdefault() - Definition, Syntax, Parameters, Examples

Definition

The setdefault() method returns the value of the item with the specified key.

If the key does not exist, insert the key, with the specified value.

Syntax

dictionary.setdefault(keyname, value)

Parameters

Parameter Description
keyname Required. The keyname of the item you want to return the value from
value Optional. If the key exist, this parameter has no effect. If the key does not exist, this value becomes the key's value. Default value None

Examples:

person = { "name": "Raymond", "age": 29, "country": "Japan" } j = person.setdefault("country", "Germany") print(j)
# example with parameters person = { "name": "Raymond", "age": 29, "country": "Japan" } k = person.setdefault("color", "brown") print(k)

Introduction

Python Basics

Python Advance

Data Science Python Tutorials

Python Functions and Methods