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. yes i know it is not the best way to do it but due to limitations in xbmc button/list functions i have no choice since i need to use dictionaries to efficiently store a lot of data.
here's the code i found but cannot get to work...
* * * *dict_set = (self.dicthsdevices, self.dicthsevents, self.dicthsbtndevices) * *<-- creates set of dictionaries
--- code examples 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
lambda/filter/map/reduce require a tutorial on their own... there is lots of talk of them being removed though since filter and map are the same as list comprehensions ( when you say [x.something for x in list] ) which are more clear. you can't do reduce though with a list comprehension but reduce is the hardest to understand of the three.
using reduce with the lambda function and a shortcircuited conditional should make that line effectively impossible to read.
really your example is much better.
* * * *for d in dict_set:
* * * * * *try:
* * * * * * * *if d.has_key(key):
* * * * * * * * * *item = d[key]
* * * * * * * * * *try: vals = d[attribs]
but what is the fastest? it must search 3 dictionaries right now, possibly more later.
i read some newsgroup posts saying this is the fastest...
[ d for d in dict_set if d[key] in dict_set ]
but i have not been able to get the syntax correct.
value = reduce(lambda x,y: (not x and y.has_key(key) and y[key]) or x, dict_set , none)
ah. got of my lazy arse and just read up on reduce() and lambda. - hard to read initially, but nice.
[ d[key] for d in dict_set if d.has_key(key)]
this will return a list though of the associated value from all dicts with the key in it. if you just want the one value i still recommend bbb's code. looking up keys in maps is plenty fast and you shouldnt worry about performance here too much.
a general software rule is that you spend 80% of your time in 20% of your code.
to find a key in multiple dicts:
dicthsdevices = {'device1':'device1_value', 'device2':'device2_value'}
dicthsevents = {'event1':'event1_value', 'event2':'event2_value'}
dicthsbtndevices = {'btndevices1':'btndevices1_value', 'btndevices2':'btndevices2_value'}
dict_set = (dicthsdevices, dicthsevents, dicthsbtndevices)
key = 'event2' # key that we want to find
value = none
for d in dict_set:
try:
value = d[key]
break
except: pass
if value:
print "found, value", value
else:
print 'not found'
its not as compact as a single line, but it works. is that what you were trying to achieve ?
#If you have any other info about this subject , Please add it free.# |