473,396 Members | 2,102 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Using 'in' with a Dict

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"

Jul 18 '05 #1
5 1392
I posted too quickly. A little performance testing told me that has_key
is somewhat slower than "in". I used a large number of string keys in
my test.

Jul 18 '05 #2
This is what I did ....
import compiler
exec1 = compiler.compile('''if "foo" in m: print "sweet"''', '', 'exec') exec2 = compiler.compile('''if m.has_key("foo"): print "dude"''', '', 'exec') exec1.co_code 'd\x01\x00e\x00\x00j\x06\x00o\t\x00\x01d\x02\x00GH n\x01\x00\x01d\x00\x00S' exec2.co_code 'e\x00\x00i\x01\x00d\x01\x00\x83\x01\x00o\t\x00\x0 1d\x02\x00GHn\x01\x00\x01d\x00\x00S' exec2 = compiler.compile('''if m.has_key("foo"): print "sweet"''', '', 'exec') exec2.co_code 'e\x00\x00i\x01\x00d\x01\x00\x83\x01\x00o\t\x00\x0 1d\x02\x00GHn\x01\x00\x01d\x00\x00S' exec(exec2) sweet exec(exec1) sweet exec1.co_varnames ('m',) exec2.co_varnames ('m', 'has_key')


The code generated with the has_key() version is slightly large (3
bytes) than the one with the membership test. The co_varnames for the
two code objects vary, as the second one has the has_key method also,
which the other version does not.

Thanks,
-Kartic

Jul 18 '05 #3
cp********@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"


To answer the question you actually asked, you can use dis.dis:

py> def f1(s, m):
.... if s in m:
.... pass
....
py> def f2(s, m):
.... if m.has_key(s):
.... pass
....
py> import dis
py> dis.dis(f1)
2 0 LOAD_FAST 0 (s)
3 LOAD_FAST 1 (m)
6 COMPARE_OP 6 (in)
9 JUMP_IF_FALSE 4 (to 16)
12 POP_TOP

3 13 JUMP_FORWARD 1 (to 17)
16 POP_TOP
17 LOAD_CONST 0 (None) 20 RETURN_VALUE
py> dis.dis(f2)
2 0 LOAD_FAST 1 (m)
3 LOAD_ATTR 1 (has_key)
6 LOAD_FAST 0 (s)
9 CALL_FUNCTION 1
12 JUMP_IF_FALSE 4 (to 19)
15 POP_TOP

3 16 JUMP_FORWARD 1 (to 20) 19 POP_TOP
20 LOAD_CONST 0 (None)

23 RETURN_VALUE

Note that in the *bytecode*, f1 uses COMPARE_OP, while f2 uses LOAD_ATTR
and CALL_FUNCTION. So no, the bytecode is different.

If the question you meant to as was "Do Python's builtin dicts use the
same code for 'in' and 'has_key'?", you can check dictobject.c:

static PyMethodDef mapp_methods[] = {
{"__contains__",(PyCFunction)dict_has_key, METH_O | METH_COEXIST,
contains__doc__},
...
{"has_key", (PyCFunction)dict_has_key, METH_O,
has_key__doc__},
...
};

Note that both __contains__ and has_key are mapped to dict_has_key. So
yes, the same C code will be executed in both cases[1].

STeVe

[1] modulo the different lookup paths to find these methods
Jul 18 '05 #4
kowboy wrote:
I posted too quickly. A little performance testing told me that has_key
is somewhat slower than "in". I used a large number of string keys in
my test.


See my other post, but the reason has_key is slower is almost certainly
that it has to do a LOAD_ATTR:

$ python -m timeit -s "m = dict.fromkeys(xrange(100, 200))" "[i in m for
i in xrange(300)]"
10000 loops, best of 3: 102 usec per loop

$ python -m timeit -s "m = dict.fromkeys(xrange(100, 200));
has_key=m.has_key" "[has_key(i) for i in xrange(300)]"
10000 loops, best of 3: 107 usec per loop

For this data at least, the difference is negligible. (I actually found
has_key to be faster in some other datasets.)

STeVe
Jul 18 '05 #5
<cp********@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>

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Benoît Dejean | last post by:
class TargetWrapper(dict): def __init__(self, **kwargs): dict.__init__(self, kwargs) __getattr__ = dict.__getitem__ __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
1
by: Alexander Kervero | last post by:
Hi ,today i was reading diveinto python book,in chapter 5 it has a very generic module to get file information,html,mp3s ,etc. The code of the example is here :...
6
by: Rick Morrison | last post by:
Would there be any way to add a method to all dict objects that operated like the .update() method, but also returned a reference to the updated dict? ..update() is clumsy to use inside of list...
0
by: Philippe C. Martin | last post by:
Hi, I have the following problem: 1) I can use smtplib to send text messages 2) I can generate html 3) I want to email the html and want it to be seen by the email client as html. However,...
4
by: Scott Baxter | last post by:
Hello, I got the following scripts to upload files to my directories I call insert.htm Browse for a file, then click 'submit' It works for small files, and for a small .mdb (access file)
3
by: Bengt Richter | last post by:
Has anyone found a way besides not deriving from dict? Shouldn't there be a way? TIA (need this for what I hope is an improvement on the Larosa/Foord OrderedDict ;-) I guess I can just document...
23
by: Brian Blais | last post by:
Hello, I have two lists, one with strings (filenames, actually), and one with a real-number rank, like: A= B= I'd like to sort list A using the values from B, so the result would be in...
7
by: wardm | last post by:
I have created a Dict object in a C++ App that calls (embedded) Python functions. The Dict is to be used to pass variable data between the C++ App and the python functions. However I cannot get...
3
by: JoJo | last post by:
Hello, I want to sort a dict via its key,but I have no idea on how to do it. Please help me,thanks. --------------------------------------------------------------------------- 3webXS HiSpeed...
0
by: rkmr.em | last post by:
the memory usage of a python app keeps growing in a x86 64 linux continuously, whereas in 32 bit linux this is not the case. Python version in both 32 bit and 64 bit linux - 2.6.24.4-64.fc8 Python...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.