Tricky Dictionary Question from newbie

James Carroll mrmaple at gmail.com
Tue Jul 12 10:09:52 EDT 2005


Oops.. Gmail just normally puts the reply to at the bottom of the
discussion... so by default I reply to the list, and the last person
to post.  My comment was not directed at you.   I just posted the
contents of an interactive session that I did to better understand
setdefault myself.  I've got to remind myself to change the reply-to
address to the list.  (other lists do this by default, why not this
one?)

I agree that the name doesn't ring quite right to me either.

I kind of understand what the creator of the function was getting
at... it's kind of like when you want to retrieve a configuration
variable from a container, but if it's not there, then you want to use
a default:

storedWidth = container.GetConfigurationValue(name = "width", default=500)

If there is a width stored, it will retrieve that, otherwise it will
give you the default that you specified in the second parameter.  It
makes it easier than checking for existance,  then retrieving or
assigning a default.

Setdefault, in my mind is really a _get_ kind of operation.  It
retrieves from the dictionary most of the time, and only does anything
different when the key doesn't exist, and then does an assignment...

so my next guess at a better name for setdefault would be:

value = container.GetOrAddDefault(key="a", default=[])
value.append(listvalue)

but that's kind of confusing too, but it better describes what is happening.

-Jim

On 7/12/05, Peter Hansen <peter at engcorp.com> wrote:
> (Fixed top-posting)
> 
> James Carroll wrote:
>  > On 7/11/05, Peter Hansen <peter at engcorp.com> wrote:
>  >>(I always have to ignore the name to think about how it works, or it
>  >>gets in the way of my understanding it.  The name makes fairly little
>  >>sense to me.)
> 
> > Notice the dictionary is only changed if the key was missing.
> 
> James, I'll assume your reply was intended to address my comment above.
>



More information about the Python-list mailing list