473,588 Members | 2,527 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

search multiple dictionaries efficiently?

I'm a noobie so please be easy on me. I have searched a ton and did not find
anything I could understand.

I'm using py2.3

I've been using Try/Except but this gets long with multiple dictionaries.

I found some code on web pages and such but cannot get them to work. Any
help is appreciated as I need to search multiple dictionaries for keys.

here's the code I found but cannot get to work...

dict_set = (self.dictHSdev ices, self.dictHSeven ts, self.dictHSbtnD evices)
<-- /creates set of dictionaries/

/code to search the set/-->

val = [ d for d in dict_set if d[value] in dict_set ]
OR
for key, value in dict.iteritems( ): pass


Jan 18 '06 #1
5 4051
"Livin" <li***@cox.ne t> wrote in message news:A3izf.418$ MJ.192@fed1read 07...
I'm a noobie so please be easy on me. I have searched a ton and did not find anything I could understand.

I'm using py2.3

I've been using Try/Except but this gets long with multiple dictionaries.

I found some code on web pages and such but cannot get them to work. Any
help is appreciated as I need to search multiple dictionaries for keys.

here's the code I found but cannot get to work...

dict_set = (self.dictHSdev ices, self.dictHSeven ts, self.dictHSbtnD evices)
<-- /creates set of dictionaries/

/code to search the set/-->

val = [ d for d in dict_set if d[value] in dict_set ]
OR
for key, value in dict.iteritems( ): pass


dict_set = [ {1:'a'}, {2:'b',3:'c'} ]
def lookup(value): .... for d in dict_set:
.... try:
.... return d[value]
.... except KeyError:
.... pass
.... raise KeyError(value)
.... lookup(1) 'a' lookup(2) 'b' lookup(3) 'c' lookup(4) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 7, in lookup
KeyError: 4

Jan 18 '06 #2
Livin wrote:
I'm a noobie so please be easy on me. I have searched a ton and did not find
anything I could understand.

I'm using py2.3

I've been using Try/Except but this gets long with multiple dictionaries.

I found some code on web pages and such but cannot get them to work. Any
help is appreciated as I need to search multiple dictionaries for keys.

here's the code I found but cannot get to work...

dict_set = (self.dictHSdev ices, self.dictHSeven ts, self.dictHSbtnD evices)
<-- /creates set of dictionaries/

/code to search the set/-->

val = [ d for d in dict_set if d[value] in dict_set ]
OR
for key, value in dict.iteritems( ): pass

If I understood correctly what you want to do, here's a one-liner that
does it:

def lookup(value, *dicts):
return [d.get(value) for d in dicts if value in d]
a = {'x':1, 'y':2}
b = {'y':4, 'z':7}
lookup('y', a, b)

[2, 4]

It's not the *most* efficient way because value is looked up twice if
it is contained in the dictionary; if you absolutely need it to be as
efficient as possible and can't figure it out on your own, ask again
and someone will help you out.

George

Jan 18 '06 #3

Livin wrote:
I'm a noobie so please be easy on me. I have searched a ton and did not find
anything I could understand.

I'm using py2.3

I've been using Try/Except but this gets long with multiple dictionaries.

I found some code on web pages and such but cannot get them to work. Any
help is appreciated as I need to search multiple dictionaries for keys.

here's the code I found but cannot get to work...

dict_set = (self.dictHSdev ices, self.dictHSeven ts, self.dictHSbtnD evices)
<-- /creates set of dictionaries/

/code to search the set/-->

val = [ d for d in dict_set if d[value] in dict_set ]
OR
for key, value in dict.iteritems( ): pass


http://aspn.activestate.com/ASPN/Coo.../Recipe/305268
http://mail.python.org/pipermail/pyt...st/294519.html

(I think these may be a little different from what you're asking above,
since they search dicts sequentially and return 1st hit)

Jan 18 '06 #4
George Sakkis wrote:
It's not the *most* efficient way because value is looked up twice if
it is contained in the dictionary; if you absolutely need it to be as
efficient as possible and can't figure it out on your own, ask again
and someone will help you out.

How do you *know* it is not the *most* efficient way? Have you tried timing
different ways of approaching this problem and found that looking up the
value twice is slow?

I've tried timing dictionary lookups in the past, and the three obvious
solutions roughly come out as follows:

try/except is fastest when the value is in the dictionary, but it is a
*lot* slower if the exception gets thrown. If missing values are a very
rare occurrence this might be a good way to do it, but usually the code
doesn't read as well so its best to avoid. [0.26/4.11]

Test with the 'in' operator and then retrieving the value is the fastest
solution when the value isn't in the dictionary (it only does a single
lookup then), and is still fast when it is. [0.36/0.2]

Using the get method of the dictionary with a default value to be retrieved
if the key is not present is slower than using the 'in' operator in all
cases (it does beat try/except when an exception is thrown) [0.49/0.54]

The numbers above are the times produced in each case for a key present/key
missing using a simple test with timeit.py.

Part of the reason, BTW, that calling d.get(key,defau lt) is slow is that is
also requires two dictionary lookups: one to find the get method and then
another to access the key in the dictionary, plus it has other overheads (a
method call) which test&get avoids.

These figures could of course be invalidated if the actual use is too far
from the simple string lookup I tried. For example if the key has a slow
hash function saving the second lookup would be worthwhile.
Jan 18 '06 #5
Duncan Booth wrote:
Test with the 'in' operator and then retrieving the value is the fastest
solution when the value isn't in the dictionary (it only does a single
lookup then), and is still fast when it is. [0.36/0.2]

Using the get method of the dictionary with a default value to be retrieved
if the key is not present is slower than using the 'in' operator in all
cases (it does beat try/except when an exception is thrown) [0.49/0.54]


Assuming those statistics are replicatable, it's quite unfortunate that
the obvious and concise way to do things works out more slowly than the
approach that you'd expect to take twice as long. Thankfully there
doesn't seem to be too many of these problems in Python.

--
Ben Sizer

Jan 18 '06 #6

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

Similar topics

10
5831
by: Bulba! | last post by:
Hello everyone, I'm reading the rows from a CSV file. csv.DictReader puts those rows into dictionaries. The actual files contain old and new translations of software strings. The dictionary containing the row data looks like this: o={'TermID':'4', 'English':'System Administration', 'Polish':'Zarzadzanie systemem'}
7
2547
by: Philipp H. Mohr | last post by:
Hello, I would like to store multiple dictionaries in a file, if possible one per line. My code currently produces a new dictionary every iteration and passes it on to another peace of code. In order to be able to re-run some experiments at a later date I would like to store every dictionary in the same file. I looked at pickel, but that seems to require a whole file for each dictionary.
3
1616
by: Oasis | last post by:
Hello, I'm new to c#. I have situation where I want to execute a number of insert statements that differ only in a few dynamic values. When I was a Java programmer, I would do this with a PreparedStatement, which will supposedly improve performance as well as make the setting of the dynamic values much more convenient than building a long sql string filled with "', '" + value1 + "', '". I think I've found the C# equivalent to the...
6
8843
by: Alex Gerdemann | last post by:
Hello, I am writing a program where I have a vector (std::vector<std:string> list) that I need to search many times. To accomplish this efficiently, I plan to sort the list using std::sort(list.begin(),list.end()), then run binary searches. I need to get the indices of the elements found so I can construct a matrix where I allocate a row of a matrix for each string in the list (row one for the first item in the list, etc). However...
22
23337
by: Matthew Louden | last post by:
I want to know why C# doesnt support multiple inheritance? But why we can inherit multiple interfaces instead? I know this is the rule, but I dont understand why. Can anyone give me some concrete examples?
5
2097
by: Jim | last post by:
Hello, I am working on a small windows application for a client, and as one of the functions they want a search that will let them enter a search string, then search a directory for all flies that contain that search string AND display the lines that contain the search string. They have windows ME, XP and 2000 systems. Does anyone have any ideas as to the most efficient way to do this?
3
3369
by: manstey | last post by:
Hi, I am running a script that produces about 450,000 dictionaries. I tried putting them into a tuple and then pickling the tuple, but the tuple gets too big. Can I pickle dictionaries one after another into the same file and then read them out again? Cheers, Matthew
9
2830
by: Daz | last post by:
Hello people! (This post is best viewed using a monospace font). I need to create a class, which holds 4 elements: std::string ItemName int Calories int Weight int Density
2
1212
by: alex.williams56 | last post by:
I'm relatively new when it comes to access but I think I have a grasp on the basics. I have a very specific problem that requires a little help from someone more experienced. I'm trying to help someone in the field of consulting create a more comprehensive database for their data they collected from surveys. Here's the background: Three surveys are sent a year, each with similar questions, but the surveys are continually revised (new...
0
7929
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8222
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
7984
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8223
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
5726
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3847
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2371
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1458
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1195
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.