Mega Code Archive

 
Categories / Python / Dictionary
 

Dictionary setdefault

#The setdefault method is somewhat similar to get, except that in addition to the get  #functionality, setdefault sets the value corresponding to the given key if it is not  #already in the dictionary: d = {} print d.setdefault('name', 'N/A') print  d d['name'] = 'Gumby' d.setdefault('name', 'N/A') print d #As you can see, when the key is missing, setdefault returns the default and updates  #the dictionary accordingly. If the key is present, its value is returned and the  #dictionary is left unchanged. The default is optional, as with get; if it is left  #out, None is used: d = {} print d.setdefault('name') print d