Python setdefault() Function

The setdefault() function in Python returns the value of given item with specified key in a dictionary. If given key does not exists, then inserts a new item with specified key and value. For example:

mydict = {"Date": "04", "Day": "Sat"}

x = mydict.setdefault("Date", "05")
print(x)

x = mydict.setdefault("Month", "Dec")
print(x)

The output will be:

04
Dec

I don't think Python has built-in functions whose name is way different than their working like setdefault(). But I think they (Python's creator) name it as setdefault(), so that to set a new item (default item), in case if the specified key does not found in the dictionary.

Python setdefault() Function Syntax

The syntax of setdefault() function in Python, is:

dictionary.setdefault(key, value)

Note: The value parameter is optional. The default value of this parameter is None. It means that, in case if the specified key is not available in dictionary, also the value parameter is not given, then a new item with specified key and None as value will get inserted into the dictionary.

The setdefault() function returns the value of specified key, if key exists in the dictionary, otherwise returns specified value. And if key does not exists, also the value does not given to setdefault(), then it returns None.

Python setdefault() Function Example

Here is an example of setdefault() function in Python:

d = {"Date": "04", "Day": "Sat"}
print("The dictionary is:", d)

d.setdefault("Month", "Dec")
print("\nNow the dictionary is:", d)

print("\nThe value of \"{}\" is \"{}\"".format("Date", d.setdefault("Date", "20")))
print("The value of \"{}\" is \"{}\"".format("Date", d.setdefault("Date")))

The snapshot given below shows the sample output produced by above program, demonstrating the setdefault() function in Python:

python setdefault function

Note: The format() function is used to format the string.

The above program can be created in this way too:

d = {"Date": "04", "Day": "Sat"}
print("The dictionary is:", d)

d.setdefault("Month", "Dec")
print("\nNow the dictionary is:", d)

str = "\nThe value of \"{}\" is \"{}\""
print(str.format("Date", d.setdefault("Date", "20")))
print(str.format("Date", d.setdefault("Date")))

Now the output is:

The dictionary is: {'Date': '04', 'Day': 'Sat'}

Now the dictionary is: {'Date': '04', 'Day': 'Sat', 'Month': 'Dec'}

The value of "Date" is "04"

The value of "Date" is "04"

Which is almost same as previous output, except that newline between last two sentence.

Python Online Test


« Previous Function Next Function »