Open In App
Related Articles

Python Dictionary setdefault() Method

Improve Article
Save Article
Like Article

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.


  • 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:


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


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


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


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.


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)


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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 25 Aug, 2022
Like Article
Save Article
Similar Reads
Complete Tutorials