Python 查找dict是否包含在另一个(新版本)中
我正在寻找一种方法来检查dict是否包含在另一个dict中:Python 查找dict是否包含在另一个(新版本)中,python,json,Python,Json,我正在寻找一种方法来检查dict是否包含在另一个dict中: big = {"result": {"code": "1000", "msg" : "oh yeah"} } small = {"result": {"code": "1000"}} test(small, big) # should be True ( small <= big ) big={“result”:{“code”:“1000”,“msg”:“oh yeah”} small={“结果”:{“代码”:“1000”}
big = {"result": {"code": "1000", "msg" : "oh yeah"} }
small = {"result": {"code": "1000"}}
test(small, big) # should be True ( small <= big )
big={“result”:{“code”:“1000”,“msg”:“oh yeah”}
small={“结果”:{“代码”:“1000”}
test(small,big)#应该是真的(small,因为您似乎是在递归地定义“包含在中”——即,如果较小dict中的每个键都存在于较大dict中,并且它们的值相同,或者较小dict的值“包含在中”,则dict包含在另一个dict中较大的递归是解决这个问题的一个明显选择
试着这样做:
def is_subset(small, large):
if isinstance(small, dict) and isinstance(large, dict):
for key in small.keys():
if not key in large:
return False
elif not is_subset(small[key], large[key]):
return False
return True
elif isinstance(small, list) and isinstance(large, list):
for s_item in small:
if not any(is_subset(s_item, l_item) for l_item in large):
return False
return True
else:
return small == large