根据条件集检查字典列表并返回匹配键

时间:2019-04-29 21:25:51

标签: python dictionary

我正在尝试在字典中进行“略读”或归约的方法,在该方法中,它将根据给定条件返回一组结果。

但是,我当前的方法更多地是一种加法,它将简单地列出满足任何条件的任何项目。

# Only list me items that are 'menuA/a100 + menuB/b100', or 'menuA/a100 + menuB/b200'
# However, there are times where I could have more than 1 menu(s) `menuX`
# condition = {'menuA':['a100']} should return only 'wrong2'
conditions = {'menuA':['a100'], 'menuB':['b100', 'b200']}

my_items = [
    {'correct' : {'menuA': ['a100'], 'menuB': ['b200']}},
    {'wrong1' : {'menuA': ['a200'], 'menuB': ['b200']}},
    {'wrong2' : {'menuA': ['a100']}},
    {'wrong3' : {'menuB': ['b100']}}
]


result = []

for m in my_items:
    for mk, mv in m.items():
        for c in conditions:
            if c in mv.keys():
                if [i for i in condition[c] if i in mv[c]]:
                    result.append(mk)

# I used `set` as it returns me `correct` twice... Even so, it is returning me every items.
print(set(result)) # set(['correct', 'wrong1', 'wrong2', 'wrong3'])

# Expecting the result to be returning me `correct`

1 个答案:

答案 0 :(得分:2)

尝试遵循您的逻辑:

result = []
for item in my_items:
    k, v = list(item.items())[0]
    if all(any(x in v.get(kc, []) for x in vc) for kc, vc in conditions.items()):
        result.append(k)

>>> print(set(result))
{'correct'}

更新:

如果您要丢弃menuconditions多的项目,这里有一个简单的解决方法:

for item in my_items:
    k, v = list(item.items())[0]
    has_same_keys = set(v) == set(conditions)
    at_least_one_value = all(
        any(x in v.get(kc, [])for x in vc) 
        for kc, vc in conditions.items())
    if has_same_keys and at_least_one_value:
        result.append(k)
相关问题