try vs. has_key()
Jeff Epler
jepler at inetnebr.com
Thu Apr 29 21:13:10 EDT 1999
On Wed, 28 Apr 1999 11:13:28 -0400 (EDT), Jeremy Hylton
<jeremy at cnri.reston.va.us> wrote:
> d={}
> for word in words:
> first_two=word[:2]
> d[first_two]=d.get(first_two, []).append(word)
>
>This second bit doesn't work because the append method on list objects
>returns None. As a result, the first time a new value for first_two
>appears None will be assigned to that key in the dictionary. The
>second time that value of first_two shows up, None will be returned by
>d.get. Then the code will raise an AttributeError, because None
>doesn't have an append method.
>
>The following code would be correct:
>
> d={}
> for word in words:
> first_two=word[:2]
> d[first_two]= temp = d.get(first_two, [])
> temp.append(word)
what about
d[first_two] = d.get(first_two, [])+[word]
? Or is list construction and addition going to be enough more expensive
than the function call to make this a lose as well?
Jeff
More information about the Python-list
mailing list