jacobcan118
jacobcan118

Reputation: 9037

check value from one dict contains from the other dict

What is the most pythonic way for me to check if value from one dictionary is subset over value of list from the other dictionary. So far I have following code However, the code is ok, if itemB's value from res is valB. But it failed, if value are valBA or 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]

Upvotes: 0

Views: 66

Answers (2)

zwer
zwer

Reputation: 25789

It's not clear what you want - to list which are subsets, or the subset values? Also, you don't need zip - since dict is an unordered set unless you can provide a clear order (which you're attempting with sorted) and if the two dicts don't have the same number and the same named keys - it will fail. It's much simpler to do it like:

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

If you need to check two levels, assuming the sub-sublevel is a list, you can do it as:

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

Upvotes: 1

Ajax1234
Ajax1234

Reputation: 71451

You can try this:

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]

Upvotes: 0

Related Questions