Home >>Python Dictionary Methods >Python Dictionary setdefault() Method

Python Dictionary setdefault() Method

Python Dictionary setdefault() Method

Python Dictionary setdefault() Method in python dictionary is used to returns the value of the specified key (if the key is in dictionary).

Syntax:
dictionary.setdefault(keyname, value)

Parameter Values

Parameter Description
keyname It is Required. The keyname of the item you want to searched for
value It is Optional. If in case the key does not exist, this value to be returned the
Here is an Example of Python Dictionary setdefault() Method:

colors = {
"color1": "red",
"color2": "blue",
"color3": "green"
}
x = colors.setdefault("colors2", "yellow")
print(x)

Output:
yellow
Example 2:

dic1 = { 'A': 'php', 'B': 'T', 'C': 'point'} 
value3= dic1.setdefault('C') 
print("Dictionary:", dic1) 
print("value3:", value3)

Output:
Dictionary: {'A': 'php', 'B': 'T', 'C': 'point'}
value3: point