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 Program to Parse a String to a Float or Int
Python Program to Remove Duplicate Element From a List
Python Program to Find the Size (Resolution) of a Image
Python Set discard()
Python String center()
Python Dictionary items()
Python List pop()
Python String rjust()
Python Deep Learning Cookbook - Indra den Bakker
Python Program to Display Powers of 2 Using Anonymous Function
Python Set difference()
Python String isnumeric()
Python Program to Measure the Elapsed Time in Python
Python sleep()
Python memoryview()
Python Variables, Constants and Literals
Python slice()
Python String find()
Python Program to Print all Prime Numbers in an Interval
Python *args and **kwargs
Python Program to Print Output Without a Newline
Python String lower()
Python Set pop()
Python String split()
Python Objects and Classes
Python Program to Split a List Into Evenly Sized Chunks
Python Program to Check Armstrong Number
Python Program to Count the Number of Occurrence of a Character in String
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python delattr()
Python String rstrip()
Python Program to Display Fibonacci Sequence Using Recursion