📜  Python – 从字典中展平和删除键

📅  最后修改于: 2022-05-13 01:55:46.849000             🧑  作者: Mango

Python – 从字典中展平和删除键

给定一个字典,执行扁平化和删除某些字典键。

方法:使用递归 + isinstance() + 循环

上述功能的组合可以用来解决这个问题。在此,我们使用 isinstance() 检查字典作为嵌套字典的实例,并且每次都为内部字典重复。循环用于迭代键。

Python3
# Python3 code to demonstrate working of
# Flatten and remove keys from Dictionary
# Using loop + recursion + isinstance()
 
# function to compute removal and flattening
def hlper_fnc(test_dict, rem_keys):
    if not isinstance(test_dict, dict):
        return test_dict
    res = {}
     
    for key, val in test_dict.items():
        rem = hlper_fnc(val, rem_keys)
         
        # performing removal
        if key not in rem_keys:
            res[key] = rem
        else:
            if isinstance(rem, dict):
                res.update(rem)
    return res
 
# initializing dictionary
test_dict = {'a': 14, 'b': 16, 'c': {'d': {'e': 7}}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing removal keys
rem_keys = ["c", "d"]
 
# calling helper function for task
res = hlper_fnc(test_dict, rem_keys)
 
# printing result
print("The removed and flattened dictionary : " + str(res))


输出原始字典为:{'a': 14, 'b': 16, 'c': {'d': {'e': 7}}}
删除和展平的字典:{'a': 14, 'b': 16, 'e': 7}