YouTip LogoYouTip

Python3 Att Dictionary Setdefault

# Python3.x Python3 Dictionary setdefault() Method [![Image 3: Python3 Dictionary](#) Python3 Dictionary](#) * * * ## Description The Python dictionary setdefault() method is similar to the [get() method](#). If the key does not exist in the dictionary, it will add the key and set the value to the default value. ## Syntax The syntax for the setdefault() method is: dict.setdefault(key, default=None) ## Parameters * key -- The key to look up. * default -- The default value to set if the key does not exist. ## Return Value If the key is in the dictionary, it returns the corresponding value. If the key is not in the dictionary, it inserts the key with the set default value `default` and returns `default`. The default value for `default` is `None`. ## Example The following example demonstrates the usage of the setdefault() method: ## Example #!/usr/bin/python3 tinydict = {'Name': 'Tutorial', 'Age': 7} print("Age The value of the key is : %s" % tinydict.setdefault('Age', None))print("Sex The value of the key is : %s" % tinydict.setdefault('Sex', None))print("The new dictionary is:", tinydict) The output of the above example is: Age The value of the key is : 7Sex The value of the key is : NoneThe new dictionary is: {'Age': 7, 'Name': 'Tutorial', 'Sex': None} * * Python3 Dictionary](#)
← Python3 Att Dictionary ValuesPython3 Att Dictionary Setdefa β†’