« All dictionary methods
setdefault(), takes two arguments , one is key and other one is value ( optional ) .
Returns : the value of the input key ( if available ) .
The original dictionary is changed after this method if the key is added.
Getting the value of the input key
my_dict={'a':'One','b':'Two','c':'Three'}
x=my_dict.setdefault('b')
print(x)
print(my_dict)
Output is here
Two
{'a': 'One', 'b': 'Two', 'c': 'Three'}
If input key is not available then key is added.
my_dict={'a':'One','b':'Two','c':'Three'}
x=my_dict.setdefault('d')
print(x)
print(my_dict)
Output (key d with value as None is added )
None
{'a': 'One', 'b': 'Two', 'c': 'Three', 'd': None}
Adding new key with value
my_dict={'a':'One','b':'Two','c':'Three'}
x=my_dict.setdefault('d','Four')
print(x)
print(my_dict)
Output
Four
{'a': 'One', 'b': 'Two', 'c': 'Three', 'd': 'Four'}
« All dictionary methods
← Subscribe to our YouTube Channel here