Table of Contents
The setdefault() method returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary.
The syntax of setdefault()
is:
dict.setdefault(key[, default_value])
1. setdefault() Parameters
setdefault()
takes a maximum of two parameters:
- key – the key to be searched in the dictionary
- default_value (optional) – key with a value default_value is inserted to the dictionary if the key is not in the dictionary.
If not provided, the default_value will beNone
.
2. Return Value from setdefault()
setdefault()
returns:
- value of the key if it is in the dictionary
- None if the key is not in the dictionary and default_value is not specified
- default_value if key is not in the dictionary and default_value is specified
3. Example 1: How setdefault() works when key is in the dictionary?
person = {'name': 'Phill', 'age': 22} age = person.setdefault('age') print('person = ',person) print('Age = ',age)
Output
person = {'name': 'Phill', 'age': 22} Age = 22
4. Example 2: How setdefault() works when key is not in the dictionary?
person = {'name': 'Phill'} # key is not in the dictionary salary = person.setdefault('salary') print('person = ',person) print('salary = ',salary) # key is not in the dictionary # default_value is provided age = person.setdefault('age', 22) print('person = ',person) print('age = ',age)
Output
person = {'name': 'Phill', 'salary': None} salary = None person = {'name': 'Phill', 'age': 22, 'salary': None} age = 22
Related posts:
Python frozenset()
Python Closures
Python Program to Check Armstrong Number
Python iter()
Python List index()
Python format()
Python String rjust()
Python Program to Check Whether a String is Palindrome or Not
Python Set discard()
Python Dictionary update()
Python len()
Python locals()
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Program to Sort Words in Alphabetic Order
Python getattr()
Python Program to Check Leap Year
Python timestamp to datetime and vice-versa
Python Program to Find Hash of File
Python Dictionary copy()
Python break and continue
Python Program to Display Calendar
Python Matrices and NumPy Arrays
Python Program to Add Two Matrices
Python Set difference()
Python Dictionary keys()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Program to Find the Size (Resolution) of a Image
Python Program to Find the Largest Among Three Numbers
Python Program to Find Factorial of Number Using Recursion
Python all()
Deep Learning with Python - Francois Cholletf
Python staticmethod()