Append a new value to dict

Kirk Strauser kirk at athena.daycos.com
Mon Oct 13 10:32:20 EDT 2008


At 2008-10-13T13:14:15Z, bearophileHUGS at lycos.com writes:

> jdd:
>> foo = {'bar': 'baz'}
>> foo.update({'quux': 'blah'})
>
> That creates a new dict, to throw it away. Don't do that.

I use that if I'm changing many values at once, eg:

    foo.update({
        'quux': 'blah',
        'baz' : 'bearophile',
        'jdd' : 'dict',
    })

instead of:

    foo['quux'] = 'blah'
    foo['baz'] = 'bearophile'
    foo['jdd'] = 'dict'

because it seems to more clearly indicate what I'm doing, and has fewer
opportunities for types.  Still, there is a performance penalty.  Running
"my way" 10,000,000 times took 8.7s, and "your way" only took 4.7s.  If
you're doing this in an inner loop, that may be significant.  While we're on
the subject, use keyword arguments to dict like:

    foo.update(dict(quux='blah', baz='bearophile', jdd='dict'))

was *much* slower, at 11.8s.
-- 
Kirk Strauser
The Day Companies



More information about the Python-list mailing list