Hi all, I am having issues with querying of dictionary items against a given set of key-value pairs. I am trying to do a ‘skimming’ or reduction method in dictionaries in which it will returns me a set of results from a given set of condition.
This is my code:
conditions = {'menuA':['a200']}
# Give me items that are menuA/a100 + menuB/b100, or menuA/a100 + menuB/b200
my_items = [
{'item01' : {'menuA': ['a100'], 'menuB': ['b200']}},
{'item02' : {'menuA': ['a200'], 'menuB': ['b200'], 'menuC' : ['c100']}},
{'item03' : {'menuA': ['a100'], 'menuB': ['b100', 'b200']}},
{'item04' : {'menuA': ['a100', 'a200']}},
{'item05' : {'menuB': ['b100'], 'menuC': ['c100']}}
]
result = []
for m in my_items:
for mk, mv in m.items():
all_conditions_met = len(conditions) == len(mv) #False
for condition in conditions:
if condition in mv:
all_conditions_met &= bool((set(mv[condition]) & set(conditions[condition])))
# Tried the following but it will fail if given condition eg. conditions = {'menuA': ['a100', 'a200'], 'menuB': ['b200']}
# where it should return me ['item01', 'item03'] but it gives me [] instead...
# all_conditions_met &= bool((set(mv[condition]) & set(conditions[condition]))) & (len(mv[condition]) == len(conditions[condition]))
else:
all_conditions_met = False
break
if all_conditions_met:
result.append(mk)
print result # 'item04'
In my above example, given the condition {'menuA':['a200']}
, it should not be returning me any results as there are no items that consists only of {'menuA':['a200']}
but yet it return me an item - closest to the given condition…
The idea behind this is to simply returns me items based on the conditions.
Could anyone give me better insights for this?