Open In App

Python Dictionary setdefault() Method

Last Updated : 25 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Python Dictionary setdefault() returns the value of a key (if the key is in dictionary). Else, it inserts a key with the default value to the dictionary.

Python Dictionary setdefault() Method Syntax:

Syntax: dict.setdefault(key, default_value)
Parameters: It takes two parameters: 

  • key – Key to be searched in the dictionary. 
  • default_value (optional) – Key with a value default_value is inserted to the dictionary if key is not in the dictionary. If not provided, the default_value will be None.

Returns: 

  • Value of the key if it is in the dictionary. 
  • None if 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.

Python Dictionary setdefault() Method Example:

Python3




d = {'a': 97, 'b': 98, 'c': 99, 'd': 100}
# space key added using setdefault() method
d.setdefault(' ', 32)
print(d)


Output:

{'a': 97, 'b': 98, 'c': 99, 'd': 100, ' ': 32}

Example 1: Using Python Dictionary setdefault() Method when key already existing in dictionary

If we use Python Dictionary setdefault() method on any existing key of a dictionary, it’ll return the value of the existing key, but will not modify the dictionary key.

Python3




d = {'a': 97, 'b': 98}
print("setdefault() returned:", d.setdefault('b', 99))
print("After using setdefault():", d)


Output: 

setdefault() returned: 98
After using setdefault(): {'a': 97, 'b': 98}

Example 2: Using Python Dictionary setdefault() Method when key not existing in dictionary

If we use setdefault() method on any non-existing key of a dictionary, it’ll return the new value added and update the dictionary with the key, value pair.

Python3




Dictionary1 = { 'A': 'Geeks', 'B': 'For'}
print("Dictionary before using setdefault():", Dictionary1)
  
# using setdefault() when key is non-existing
ret_value = Dictionary1.setdefault('C', "Geeks")
print("Return value of setdefault():", ret_value)
  
print("Dictionary after using setdefault():", Dictionary1)


Output: 

Dictionary before using setdefault(): {'A': 'Geeks', 'B': 'For'}
Return value of setdefault(): Geeks
Dictionary after using setdefault(): {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads