setdefault() method of dictionary

All dictionary methods

setdefault(), takes two arguments , one is key and other one is value ( optional ) .

Returns : the value of the input key ( if avilable ) .

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


plus2net.com



Post your comments , suggestion , error , requirements etc here





Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer