简体   繁体   中英

Given key-value pair(s), derive the item from a dictionary

I apologize in advance if my post is at the wrong thread. I seem to have got myself confused in this tagging 'system' that I am trying to do, that, or the logic has strayed in the use of dictionaries as my conditions can have multiple keys/ values...

At the moment, the results that I am trying to achieve is only possible if I only stick to the use of either and or or method but yet I am trying to achieve both, if possible.

#conditions = {'motions': ['walk']}
#conditions = {'motions': ['run']}
conditions = {'motions': ['run', 'walk']}

# 1. if only 'run', item02 and item04 should be shown
# 2. if only 'walk' + 'run', item04 should be shown


my_items = [
     {'item01' : {'motions': ['walk']}},
     {'item02' : {'motions': ['run']}},
     {'item03' : {'motions': ['crawl']}},
     {'item04' : {'motions': ['run', 'walk']}},
]

result = []

for m in my_items:
    for mk, mv in m.items():
        res1 = all(any(x in mv.get(kc, []) for x in vc) for kc, vc in conditions.items())

        all_conditions_met = len(conditions) == len(mv) #False
        for cond in conditions:
            if cond in mv:
                res2 = all_conditions_met and (set(mv[cond]) == set(conditions[cond]))
                all_conditions_met = bool(res1 and res2)

                # # if I use bool(res1 and res2)
                # returns me only item02, incorrect for #1
                # returns me only item04, correct for #2

                # if I use bool(res1 or res2)
                # returns me item02 and item04, incorrect for #1
                # returns me item01, item02 and item04, incorrect for #2

            else:
                all_conditions_met = False
                break
        if all_conditions_met:
            result.append(mk)

Could someone kindly share some insights?

If you're looking for full matches, then you should check for all , not any . In fact, you are trying to check whether a set is a subset of another one -- and you can benefit from Python's built-in set type :

names = []
for row in my_items:
  for name, subconditions in row.items():
    full_match = all(
      set(conditions[key]) <= set(subconditions.get(key, []))
      for key in conditions.keys()
    )

    if full_match:
      names.append(name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM