Worthwhile to reverse a dictionary

Mike Meyer mwm at mired.org
Thu Dec 15 03:38:53 CET 2005


Erik Max Francis <max at alcyone.com> writes:
> rudysanford at hotmail.com wrote:
>> What is the difference between
>>  " d1 = {'A' : '1', 'B' : '2', 'C' : '3'} "
>> and
>> " d1 = dict(A = 1, B = 2, C = 3) "  ?
>> All of the dictionary examples I saw (python.org,
>> aspn.activestate.com,
>> Learning Python by Lutz, among others) use d={'x' : 'y'}.
>
> In the latter case the values are ints, whereas in the former they are
> strings.  But you probably didn't mean that; indeed it is the case that
> 	d1 = {'A': 1, 'B': 2, 'C': 3}
> and
> 	d2 = dict(A=1, B=2, C=3)
> are equivalent.

Not quite:

>>> def f():
...  a = {'a': 1, 'b': 2}
...  b = dict(a = 1, b = 2)
... 
>>> dis.dis(f)
  2           0 BUILD_MAP                0
              3 DUP_TOP             
              4 LOAD_CONST               1 ('a')
              7 LOAD_CONST               2 (1)
             10 ROT_THREE           
             11 STORE_SUBSCR        
             12 DUP_TOP             
             13 LOAD_CONST               3 ('b')
             16 LOAD_CONST               4 (2)
             19 ROT_THREE           
             20 STORE_SUBSCR        
             21 STORE_FAST               0 (a)

  3          24 LOAD_GLOBAL              1 (dict)
             27 LOAD_CONST               1 ('a')
             30 LOAD_CONST               2 (1)
             33 LOAD_CONST               3 ('b')
             36 LOAD_CONST               4 (2)
             39 CALL_FUNCTION          512
             42 STORE_FAST               1 (b)
             45 LOAD_CONST               0 (None)
             48 RETURN_VALUE        


The first form builds the dict in place, and assigns the result. The
second form invokes the "dict" object on the keyword arguments, which
function then builds the dict. They have the same effect, provided no
one has shadowed the definition of the builtin "dict" function.

    <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list