Python - 嵌套字典子集
给定一个嵌套字典,测试另一个字典是否是子集。
例子:
Input : test_dict = {“gfg”: 12, ‘best’ : {1 : 3, 4 : 3, ‘geeks’ : {8 : 7}}}, sub_dict = {8 : 7}
Output : True
Explanation : Required Nested dictionary present in Dictionary.
Input : test_dict = {“gfg”: 12, ‘best’ : {1 : 3, 4 : 3, ‘geeks’ : {8 : 7}}}, sub_dict = {9 : 7}
Output : False
Explanation : Nested dictionary not present in Dictionary.
方法:使用all() + any() + isinstance() +递归
在此,我们使用函数在每个嵌套中检查子集,并使用 all() 检查所有键匹配,any() 用于该实用程序以测试与测试字典上的测试子集匹配的任何嵌套可能子集。每个嵌套都使用递归进行测试。
Python3
# Python3 code to demonstrate working of
# Nested Dictionary Subset Python
# Using all() + any() + isinstance() + recursion
def check_eq(mast_dict, subdict):
if not isinstance(mast_dict, (dict, list)):
return mast_dict == subdict
if isinstance(mast_dict, list):
# check for nesting dictionaries in list
return all(check_eq(x, y) for x, y in zip(mast_dict, subdict))
# check for all keys
return all(mast_dict.get(idx) == subdict[idx] or check_eq(mast_dict.get(idx), subdict[idx]) for idx in subdict)
def is_subset(mast_dict, subdict):
if isinstance(mast_dict, list):
# any matching dictionary in list
return any(is_subset(idx, subdict) for idx in mast_dict)
# any matching nested dictionary
return check_eq(mast_dict, subdict) or (isinstance(mast_dict, dict) and any(is_subset(y, subdict) for y in mast_dict.values()))
# initializing dictionary
test_dict = {"gfg": 12, 'best': {1: 3, 4: 3, 'geeks': {8: 7}}, 'cs': 7}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing subset dict
sub_dict = {8: 7}
# calling func
res = is_subset(test_dict, sub_dict)
# printing result
print("Is dictionary subset : " + str(res))
输出:
The original dictionary is : {‘gfg’: 12, ‘best’: {1: 3, 4: 3, ‘geeks’: {8: 7}}, ‘cs’: 7}
Is dictionary subset : True