Python dict setdefault function | Example code

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.

dictionary.setdefault(keyname, 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}

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

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.