我已經為我的問題嘗試了這個答案: Match dictionary by a filter (other 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.
uj5u.com熱心網友回復:
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
它回傳 True,因為( ) 中的foo1key下的值與 key下的相同鍵值對存在于相同的 key-value 對中。myfilter{"sub_foo" : "sub_bar"}mydictmy_dictfoo1
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/441379.html
下一篇:將字典值解包到函式引數中
