search multiple dictionaries efficiently?

Paul McGuire ptmcg at austin.rr._bogus_.com
Wed Jan 18 05:09:18 CET 2006


"Livin" <livin at cox.net> wrote in message news:A3izf.418$MJ.192 at fed1read07...
> 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.dictHSdevices, self.dictHSevents, self.dictHSbtnDevices)
> <-- /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
>>>





More information about the Python-list mailing list