对于我来说,检查一个字典中的值是否是来自另一个字典的列表值的子集的最pythonic方法是什么。到目前为止,我有以下代码 但是,如果来自res的itemB&#39的值是valB,则代码是可以的。但如果值为valBA或valBB,则失败。
exp = dict(itemA = ['valA1', 'valA2'], itemB = ['valB', ['valBA', 'valBB']], itemC = ['valC1', 'valC2'])
res = dict(itemA = 'valA1', itemB = 'valBA', itemC = 'valC1')
for e, r in zip(sorted(exp), sorted(res)):
if r == 'itemB':
return any(res[r] in s for s in exp[e][0])
else:
return res[r] in exp[e]
答案 0 :(得分:1)
不清楚你想要什么 - 列出哪些子集或子集值?此外,您不需要拉链 - 因为dict
是一个无序集合,除非您可以提供明确的订单(您正在尝试排序)并且如果这两个指令不具备相同的数字和相同的命名键 - 它将失败。这样做要简单得多:
exp = dict(itemA=['valA1','valA2'],itemB=['valB',['valBA','valBB']],itemC=['valC1','valC2'])
res = dict(itemA='valA1',itemB='valBA',itemC='valC1')
subsets = [k for k, v in res.items() if v in exp.get(k, {})]
# ['itemC', 'itemA']
subset_values = [v for k, v in res.items() if v in exp.get(k, {})]
# ['valA1', 'valC1']
# to check if all subsets exist
all_subsets = all(v in exp.get(k, {}) for k, v in res.items())
# False
如果您需要检查两个级别,假设子级别是一个列表,您可以这样做:
subsets = []
for group, value in res.items():
for subgroup in exp.get(group, []):
if value == subgroup or (isinstance(subgroup, list) and value in subgroup):
subsets.append(group) # or append value if you're after that
break
# ['itemA', 'itemB', 'itemC']
# or to check if all matched:
all_subsets = len(subsets) == len(exp)
# True
答案 1 :(得分:0)
你可以试试这个:
exp = dict(itemA = ['valA1', 'valA2'], itemB = ['valB', ['valBA', 'valBB']], itemC = ['valC1', 'valC2'])
res = dict(itemA = 'valA1', itemB = 'valBA', itemC = 'valC1')
new_vals = [a for a, b in zip(res.values(), exp.values()) if a in b]