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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With