updating dictionaries from/to dictionaries
John Machin
sjmachin at lexicon.net
Mon Aug 11 05:06:00 EDT 2008
On Aug 11, 6:24 pm, "Calvin Spealman" <ironfro... at gmail.com> wrote:
> for k in foo:
> foo[k] += bar.get(k, 0)
An alternative:
for k in bar:
foo[k] += bar[k]
The OP asserts that foo keys are a superset of bar keys. If that
assertion is not true (i.e. there are keys in bar that are not in foo,
your code will silently ignore them whereas mine will cause an
exception to be raised (better behaviour IMHO). If the assertion is
true, mine runs faster (even when len(foo) == len(bar).
More information about the Python-list
mailing list