Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




setdefault( ) FUNCTION


The setdefault( ) Function sets a default value for an Entry(i.e. A Key Value pair) in the 'Dictionary'.


Example :


x = {
    5 : "Is a Number", 
    "John": "Is a Name", 
    "Python": "Is a Language"
}
x.setdefault("Rose", "Is a Flower")
print(x)


Output :



  {5: 'Is a Number', 'John': 'Is a Name', 'Python': 'Is a Language', 'Rose': 'Is a Flower'}

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'.


java_Collections

Then we have used the 'setdefault( )' Function to set a default value for the 'Key', 'Rose'.


x.setdefault("Rose", "Is a Flower")

And, since the Key, 'Rose' is not present in the Dictionary. The Key, 'Rose' is added with the default value 'Is a Flower'.


java_Collections

And if you see the Output, 'x' contains all the four entries.


Output :



  {5: 'Is a Number', 'John': 'Is a Name', 'Python': 'Is a Language', 'Rose': 'is a Flower'}

And if the entry with the 'Key' "Rose" is already present. No change is made to it.


Example :


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)


Output :



  {5: 'Is a Number', 'John': 'Is a Name', 'Python': 'Is a Language', 'Rose': 'Is a red Flower'}