Dict when defining not returning multi value key error

Chris Angelico rosuav at gmail.com
Thu Jul 31 18:23:19 EDT 2014


On Fri, Aug 1, 2014 at 7:29 AM, Emile van Sebille <emile at fenx.com> wrote:
> And which is also how it works:
>
> Python 2.5 (r25:51908, Dec 18 2009, 14:22:21)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>>
>>>> def test():p = {'k':"value0",'k':"value1"}
> ...
>>>> from dis import dis
>>>> dis(test)
>   1           0 BUILD_MAP                0
>               3 DUP_TOP
>               4 LOAD_CONST               1 ('value0')
>               7 ROT_TWO
>               8 LOAD_CONST               2 ('k')
>              11 STORE_SUBSCR
>              12 DUP_TOP
>              13 LOAD_CONST               3 ('value1')
>              16 ROT_TWO
>              17 LOAD_CONST               2 ('k')
>              20 STORE_SUBSCR
>              21 STORE_FAST               0 (p)
>              24 LOAD_CONST               0 (None)
>              27 RETURN_VALUE

Python 2.5 is quite old now, but here's the 2.7 disassembly for the same code:

>>> dis.dis(test)
  1           0 BUILD_MAP                2
              3 LOAD_CONST               1 ('value0')
              6 LOAD_CONST               2 ('k')
              9 STORE_MAP
             10 LOAD_CONST               3 ('value1')
             13 LOAD_CONST               2 ('k')
             16 STORE_MAP
             17 STORE_FAST               0 (p)
             20 LOAD_CONST               0 (None)
             23 RETURN_VALUE

I believe it's still doing the same thing. My reading of this is:
"Create a map with room for two elements. Stick this value on the
stack, stick this key on the stack, stow it in the map. Repeat last
sentence with a different value. Now store that resulting map." So
it's still just happily overriding, although the code is different
from the assignment version:

>>> dis.dis(test2)
  1           0 BUILD_MAP                0
              3 STORE_FAST               0 (p)
              6 LOAD_CONST               1 ('value0')
              9 LOAD_FAST                0 (p)
             12 LOAD_CONST               2 ('k')
             15 STORE_SUBSCR
             16 LOAD_CONST               3 ('value1')
             19 LOAD_FAST                0 (p)
             22 LOAD_CONST               2 ('k')
             25 STORE_SUBSCR
             26 LOAD_CONST               0 (None)
             29 RETURN_VALUE

ChrisA



More information about the Python-list mailing list