Using 'in' with a Dict
Fredrik Lundh
fredrik at pythonware.com
Wed Feb 16 16:57:17 EST 2005
<cpmcdaniel at gmail.com> wrote:
>I was wondering if the following two "if" statements compile down to
> the same bytecode for a standard Dictionary type:
>
> m = {"foo": 1, "blah": 2}
>
> if "foo" in m:
> print "sweet"
>
> if m.has_key("foo"):
> print "dude"
nope.
>>> import dis
>>> dis.dis(compile("'foo' in dict", "", "exec"))
1 0 LOAD_CONST 0 ('foo')
3 LOAD_NAME 0 (dict)
6 COMPARE_OP 6 (in)
9 POP_TOP
10 LOAD_CONST 1 (None)
13 RETURN_VALUE
>>> dis.dis(compile("dict.has_key('foo')", "", "exec"))
1 0 LOAD_NAME 0 (dict)
3 LOAD_ATTR 1 (has_key)
6 LOAD_CONST 0 ('foo')
9 CALL_FUNCTION 1
12 POP_TOP
13 LOAD_CONST 1 (None)
16 RETURN_VALUE
"in" is a built-in operator, "has_key" is an ordinary method. both
paths end up in the same C function, but the method path is usually
a little bit slower.
</F>
More information about the Python-list
mailing list