Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any benefit to returning a hash constructed with dict rather than just using the curly braces syntax?

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.

like image 648
Geo Avatar asked Nov 28 '22 23:11

Geo


2 Answers

>>> 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.

like image 166
ephemient Avatar answered Dec 10 '22 07:12

ephemient


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.

like image 36
S.Lott Avatar answered Dec 10 '22 09:12

S.Lott