The setdefault( ) Function sets a default value for an Entry(i.e. A Key Value pair) in the 'Dictionary'.
x = {
5 : "Is a Number",
"John": "Is a Name",
"Python": "Is a Language"
}
x.setdefault("Rose", "Is a Flower")
print(x)
So, in the above code we have created a 'Dictionary' using braces '{ }' and 'Key' and 'Value' pairs.
x = {
5 : "Is a Number",
"John": "Is a Name",
"Python": "Is a Language"
}
And initialised to the variable 'x'.
Function1.png)
Then we have used the 'setdefault( )' Function to set a default value for the 'Key', 'Rose'.
And, since the Key, 'Rose' is not present in the Dictionary. The Key, 'Rose' is added with the default value 'Is a Flower'.
Function2.png)
And if you see the Output, 'x' contains all the four entries.
And if the entry with the 'Key' "Rose" is already present. No change is made to it.
x = {
5 : "Is a Number",
"John": "Is a Name",
"Python": "Is a Language"
"Rose": "Is a red Flower"
}
x.setdefault("Rose", "is a Flower")
print(x)