How to Use Dictionary setdefault() Method in PythonPython Basics


The setdefault() method returns the value of the specified key if the value is not in the dictionary, otherwise the default value.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

dict1 = {'Name': 'Volkswagen', 'Vehicle type': 'SUV','Turbo':'no','Price': 150000}
print(dict1)

print ("the value of key Price is : %s" %dict1.setdefault('Price', 0))
print(dict1)

print ("the value of key gearbox is : %s" %dict1.setdefault('gearbox', None))
print(dict1)

Output:

{'Name': 'Volkswagen', 'Vehicle type': 'SUV', 'Turbo': 'no', 'Price': 150000}
the value of key Price is : 150000
{'Name': 'Volkswagen', 'Vehicle type': 'SUV', 'Turbo': 'no', 'Price': 150000}
the value of key gearbox is : None
{'Name': 'Volkswagen', 'Vehicle type': 'SUV', 'Turbo': 'no', 'Price': 150000, 'gearbox': None}

Syntax

dictionary.setdefault(key[, default_value])

Parameters

Name Description
key The key value of the lookup.
default_value The default value to be returned if the key is not in the dictionary.

Return Value

It returns the values of the specified key if the value is not in the dictionary, otherwise it returns the default value.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us