用另一个字典过滤一个字典的字典

Filter a dictionary of dictionaries by another dictionary

我试过这个答案来解决我的问题:

这是我使用的代码:

    
mydict = {'foo' : 'bar', 'foo1' : {"sub_foo" : 'sub_bar', "sub_foo1" : "sub_bar1"}}

myfilter = {'foo1' : {"sub_foo" : "sub_bar"}}


setf = set(myfilter.items()) # save space
if setf == (set(mydict.items()) & setf): # if pass 
    print(mydict)

我收到这个错误:

Traceback (most recent call last):
  File "c:\Users\basti\Documents\IVAO and VATSIM py wrapper\python-ivao\simple_test.py", line 29, in <module>
    setf = set(myfilter.items()) # save space
TypeError: unhashable type: 'dict'

我想知道过滤器 sub_dict 是否包含在 dict 中。

IIUC,你可以遍历 myfilter 并检查其中的值是否是 mydict:

中具有相同键的值的子集
for k1, v1 in myfilter.items():
    if isinstance(v1, dict):
        print(set(v1.items()).issubset(mydict.get(k1, {}).items()))
    elif isinstance(v1, (str, int, float)):
        print(v1 in mydict.get(k1, {}))

输出:

True

它 returns 正确,因为 foo1 键下的值 myfilter ({"sub_foo" : "sub_bar"}) 存在于 mydict 中,与 key-value 相同在 my_dict 中配对也在 foo1 键下。