Python dictionary setdefault() Method


Contents

Description

Python dictionary method setdefault() is alike to get(), yet will put dict[key]=default if input is not previously in dict. In Python vocabulary, setdefault() method arrivals the value of a key (if the key is in dictionary). If not, it introduces key with a charge to the dictionary. ... key – Key to be looked in the dictionary. default_value (optional) – Key with a charge default_value is inserted to the vocabulary if key is not in the dictionary.

Syntax

Following is the syntax for setdefault() method:

dict.setdefault(key, default=None)

Parameters

  • key − This is the key to be searched.

  • default − This is the Value to be returned in case key is not found.

Return Value

This method returns the key value available in the dictionary and if given key is not available then it will return provided default value.

Example

The following example shows the usage of setdefault() method.

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" %  dict.setdefault('Age', None)
print "Value : %s" %  dict.setdefault('Sex', None)

When we run above program, it produces following result:

Value : 7
Value : None

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.



Navigation
Tutorial
Tutorial
Tutorial