Python Dictionary (Dictionary) setdefault () method, pythonsetdefault
Description
The Python Dictionary (Dictionary) setdefault () function is similar to the get () method. If the key does not exist in the Dictionary, a key is added and the value is set to the default value.
Syntax
Setdefault () method Syntax:
Dict. setdefault (key, default = None)
Parameters
- Key -- the key value to be searched.
- Default -- if the key does not exist, the default key value is set. If the key exists, it is not set.
Return Value
This method does not return any values.
Instance
The following example shows how to use the setdefault () function:
#! /Usr/bin/pythondict = {'name': 'zara ', 'age': 7}
Dict_default = dict. setdefault ('sex', 'man ')
Print "Value: % s" % dict. setdefault ('age', None) print "Value: % s" % dict. setdefault ('sex', 'Man ')
The output result of the above instance is:
Value: 7 Value: None
>>> Dict_default
>>> Man
>>> Dict =
{'Name': 'zara ', 'age': 7, 'sex': 'man '}