Skip to content

Python dict setdefault function | Example code

  • by

The Python dict setdefault method is used to get the value of the item with the specified key. This method actually returns the value of a key (if the key is in a dictionary). If not, it inserts a key with a value to the dictionary.

dict.setdefault(key, default_value)
  • If the key is present in the dictionary, setdefault() returns its corresponding value.
  • If the key is not present in the dictionary, setdefault() inserts the key with the specified default_value and returns default_value.

Python dict setdefault example

Simple example code how setdefault() works when the key is in the dictionary.

person = {'name': 'Jack', 'age': 25}
print(person)

age = person.setdefault('age')

print('Age = ', age)

Output:

Python dict setdefault function

Another example, if the key is not in the dictionary

person = {'name': 'Jack', 'age': 25}
print(person)

salary = person.setdefault('salary')
print(person)

Output:

{‘name’: ‘Jack’, ‘age’: 25}
{‘name’: ‘Jack’, ‘age’: 25, ‘salary’: None}

Comment if you have any doubts or suggestions on this Python dictionary function.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading