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 complex()
Python Directory and Files Management
Python Program to Find Armstrong Number in an Interval
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python eval()
Python pow()
Python Tuple index()
Python String translate()
Python callable()
Python sorted()
Deep Learning with Python - Francois Cholletf
Python Dictionary fromkeys()
Python Anonymous / Lambda Function
Python Program to Find the Size (Resolution) of a Image
Python round()
Python String rpartition()
Python delattr()
Python Program to Check If Two Strings are Anagram
Python Program to Create Pyramid Patterns
Python String maketrans()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Functions
Python Program to Convert Kilometers to Miles
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Dictionary keys()
How to get current date and time in Python?
Python String isnumeric()
Python String center()
Python List
Python staticmethod()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python String rindex()