try vs. has_key()

William H. Duquette William.H.Duquette at jpl.nasa.gov
Wed Apr 28 18:23:00 EDT 1999


On Wed, 28 Apr 1999 14:58:13 GMT, William.H.Duquette at jpl.nasa.gov
(William H. Duquette) wrote:


>>>> d = {}
>>>> a = 'Foo'
>>>> d[a] = d.get(a, []).append('Bar')
>>>> d
>{'Foo': None}
>>>>
>
>I'd have expected to see {'Foo': 'Bar'}, but that's not what I get.


As someone pointed out, append() returns None, explaining
the result I got.  However, the following code works just fine:

 d = {}
 a = 'foo'

 # Append an entry to d[a], whether it has been initialized or not:
 d[a] = d.get(a, [])
 d[a].append('Bar')


Will

--------------------------------------------------------------------------
Will Duquette, JPL  | William.H.Duquette at jpl.nasa.gov
But I speak only    | http://eis.jpl.nasa.gov/~will (JPL Use Only)
for myself.         | It's amazing what you can do with the right tools.




More information about the Python-list mailing list