try vs. has_key()
Jeremy Hylton
jeremy at cnri.reston.va.us
Thu Apr 29 10:44:06 EDT 1999
>>>>> "WD" == William H Duquette <William.H.Duquette at jpl.nasa.gov> writes:
WD> As someone pointed out, append() returns None, explaining the
WD> 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')
However, you're doing two dictionary lookups when only one is
necessary. It would be more efficient to store the results of the get
in a temporary variable -- temp = d[a] = d.get(a, []) -- and use the
temporary variable for the append.
Jeremy
More information about the Python-list
mailing list