In some Python code I've read I keep noticing this code:
return dict(somekey=somevalue)
Does that have any benefit over:
return {somekey:somevalue}
I tend to say no, since both objects will belong to the same dict
type, but I may be wrong.
>>> def foo(): return dict(a=1) ... >>> def bar(): return {'a':1} ... >>> import dis >>> dis.dis(foo) 1 0 LOAD_GLOBAL 0 (dict) 3 LOAD_CONST 1 ('a') 6 LOAD_CONST 2 (1) 9 CALL_FUNCTION 256 12 RETURN_VALUE >>> dis.dis(bar) 1 0 BUILD_MAP 1 3 LOAD_CONST 1 (1) 6 LOAD_CONST 2 ('a') 9 STORE_MAP 10 RETURN_VALUE >>> import timeit >>> timeit.Timer(foo).timeit() 0.76093816757202148 >>> timeit.Timer(bar).timeit() 0.31897807121276855
There is no functional difference, but the latter is more efficient.
They are semantically identical.
The dict( param=value, ... )
notation limits your keys to strings which are valid python identifiers.
The dict( sequence-of-2-tuples )
is effectively the same as {}
.
The {}
notation places no limits on the keys. Except that they be hashable objects.
There are performance differences.
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