Monday, February 23, 2026
HomeLanguagesPython Dictionary setdefault() Method

Python Dictionary setdefault() Method

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'}
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32506 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6882 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12099 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7255 POSTS0 COMMENTS
Thapelo Manthata
6967 POSTS0 COMMENTS
Umr Jansen
6956 POSTS0 COMMENTS