Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, use "dict" with keywords or anonymous dictionaries? [closed]

Tags:

python

Say you want to pass a dictionary of values to a function, or otherwise want to work with a short-lived dictionary that won't be reused. There are two easy ways to do this:

Use the dict() function to create a dictionary:

foo.update(dict(bar=42, baz='qux'))

Use an anonymous dictionary:

foo.update({'bar': 42, 'baz': 'qux'})

Which do you prefer? Are there reasons other than personal style for choosing one over the other?

like image 460
Kirk Strauser Avatar asked Dec 18 '09 16:12

Kirk Strauser


2 Answers

I prefer the anonymous dict option.

I don't like the dict() option for the same reason I don't like:

 i = int("1")

With the dict() option you're needlessly calling a function which is adding overhead you don't need:

>>> from timeit import Timer
>>> Timer("mydict = {'a' : 1, 'b' : 2, 'c' : 'three'}").timeit()
0.91826782454194589
>>> Timer("mydict = dict(a=1, b=2, c='three')").timeit()
1.9494664824719337
like image 154
Dave Webb Avatar answered Oct 14 '22 14:10

Dave Webb


I think in this specific case I'd probably prefer this:

foo.update(bar=42, baz='qux')

In the more general case, I often prefer the literal syntax (what you call an anonymous dictionary, though it's just as anonymous to use {} as it is to use dict()). I think that speaks more clearly to the maintenance programmer (often me), partly because it stands out so nicely with syntax-highlighting text editors. It also ensures that when I have to add a key which is not representable as a Python name, like something with spaces, then I don't have to go and rewrite the whole line.

like image 44
Peter Hansen Avatar answered Oct 14 '22 15:10

Peter Hansen