dictionary initialization

Josiah Carlson jcarlson at uci.edu
Thu Nov 25 17:13:22 EST 2004


wgshi at namao.cs.ualberta.ca (Weiguang Shi) wrote:
> 
> In article <lIydnVF-WvXK3TvcRVn-jA at rogers.com>, Dan Perl wrote:
> >I don't know awk, so I don't know how your awk statement works.
> It doesn't hurt to give it a try :-)
> 
> >
> >Even when it comes to the python statements, I'm not sure exactly what the 
> > ...
> I see your point.
> 
> >
> >You're saying that in awk a['hello'] is initialized to 0.  
> More than that; I said awk recognizes a['hello']++ as an
> arithmetic operation and initializes a['hello'] to 0 and add one to
> it. (This is all guess. I didn't implement gawk. But you see my point.)
> 
> > That would not be justified in python.  The type of b[1] is
> > undetermined until initialization and I don't see why it should be
> > an int by default.
> In my example, it was b[1]+=1. "+=1" should at least tell Python two
> things: this is an add operation and one of the operands is an
> integer. Based on these, shouldn't Python be able to insert the pair
> "1:0" into a{} before doing the increment?

As Peter has already mentioned, since b[1] doesn't exist until you
assign it, the type of b[1] is ambiguous.

The reason Python doesn't do automatic assignments on unknown access is
due to a few Python 'Zens'

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Specifically:
Explicit is better than implicit.
  (you should assign what you want, not expect Python to know what you
  want)
Special cases aren't special enough to break the rules.
  (incrementing non-existant values in a dictionary shouldn't be any
  different from accessing non-existant values)
In the face of ambiguity, refuse the temptation to guess.
  (what class/value should the non-existant value initialize to?)


Learn the zens.  Any time you have a design question about the Python,
check the zens, then check google, then check here.

 - Josiah




More information about the Python-list mailing list