Answers for "python dict setdefault"

5

set default python

newDict = {1:"One",
           2:"Two",
           3:"Three"}
x=newDict.setdefault(4,"Four")
print(newDict[4])
#returns Four

newDict2 = {1:"One",
           2:"Two",
           3:"Three",
           "Hello":"World"}
y=newDict.setdefault("Hello","Yellow")
print(newDict2["Hello"])
#returns World

dict1 = {1:"One",2:"Two"}
x=dict1.setdefault(3,"Three")
x=dict1.setdefault(2,"Duo")
print(dict1)
#prints {1: 'One', 2: 'Two', 3: 'Three'}

#Therefore if value doesn't exist it is given default value, else value of key is returned.
Posted by: Guest on September-18-2020
0

python dictonary set default

#!/usr/bin/python

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

>>Value : 7
>>Value : None
Posted by: Guest on November-02-2021

Python Answers by Framework

Browse Popular Code Answers by Language