[Tutor] setdefault method
Carroll, Barry
Barry.Carroll at psc.com
Tue Mar 28 00:48:16 CEST 2006
Greetings:
What is the purpose of the dictionary method setdefault(k[, x])?
For example assume the following dictionary:
>>> colors = {'green':(0,255,0), 'red':(255,0,0), 'blue':(0,0,255), 'white':(255,255,255), 'black':(0,0,0)}
>>>
Now, execute the statement:
>>> colors.setdefault('black')
(0, 0, 0)
>>>
I would expect that future references to colors, with no argument or a null argument, would return the value of colors['black'], e.g.:
>>> colors[]
(0, 0, 0)
>>> colors
(0, 0, 0)
>>>
or some similar syntax. This is not the case, however. The actual behavior is:
>>> colors
{'blue': (0, 0, 255), 'black': (0, 0, 0), 'white': (255, 255, 255), 'green': (0, 255, 0), 'red': (255, 0, 0)}
>>> colors[]
File "<input>", line 1
colors[]
^
SyntaxError: invalid syntax
>>>
So, what then is the proper use of setdefault()? And, if d.setdefault does not actually assign a default value for d, is there a way to do this?
As always, thanks in advance for your responses.
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
More information about the Tutor
mailing list