From: jepler at inetnebr.com (Jeff Epler) Date: Fri, 30 Apr 1999 01:13:10 GMT Subject: try vs. has_key() References: <7g51q6$1pt$1@vvs.superst.iae.nl> <14119.8145.293039.667256@bitdiddle.cnri.reston.va.us> Message-ID: X-UID: 120 On Wed, 28 Apr 1999 11:13:28 -0400 (EDT), Jeremy Hylton 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