I have tried this answer for my problem: Match dictionary by a filter (other dictionary)
Here is the code I use :
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)
I get this error :
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'
I would like to have a way to tell if the filter sub_dict
is included in the dict
.
CodePudding user response:
IIUC, you could traverse myfilter
and check if a value in it is a subset of the value with the same key in 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, {}))
Output:
True
It returns True because the value under foo1
key in myfilter
({"sub_foo" : "sub_bar"}
) exists in mydict
as the same key-value pair in my_dict
also under foo1
key.