📜  Python - 从字典嵌套中删除 K 值项

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

Python - 从字典嵌套中删除 K 值项

给定具有多个嵌套的字典,删除所有值为 K 的键。

方法#1:使用循环+字典理解

上述功能的组合可以用来解决这个问题。在此,我们使用循环迭代所有嵌套键。并删除值。这种方法适用于字典的单级嵌套。

Python3
# Python3 code to demonstrate working of 
# Remove K value items from dictionary nestings
# Using dictionary comprehension + loop
  
# initializing list
test_list = [{"Gfg" : {"a" : 5, "b" : 8, "c" : 9}},
             {"is" : {"f" : 8, "j" : 8, "k" : 10}},
             {"Best" : {"i" : 16}}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 8
  
res = list()
  
for sub in test_list:
    for key, val in sub.items():
          
        # iterating for 1st nesting only
        for key1, val1 in val.items():
            if val1 != K:
                res.append({key1 : val1})
  
# printing result 
print("The dictionary after value removal : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Remove K value items from dictionary nestings
# Using recursion + loop (For multiple nesting)
  
res = []
  
# helper function to solve problem
def hlper_fnc(test_dict):
    for key in test_dict:
        if type(test_dict[key]) == dict:
            hlper_fnc(test_dict[key])
        else:
            if test_dict[key] != K:
                res.append({key : test_dict[key]})
  
# initializing dictionary
test_dict = {"Gfg" : {"a" : 5, "b" : 8, "c" : 9},
             "is" : {"f" : 8, "l" : { "j" : 8, "k" : 10}},
             "Best" : {"i" : {"k" : { "o" : 8}}}}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 8
  
# computing result
hlper_fnc(test_dict)
  
# printing result 
print("The dictionary after value removal : " + str(res))


输出

方法#2:使用递归+循环(用于多重嵌套)

这是可以执行此任务的另一种方式。在此,我们解决了一个更通用的问题,即迎合内部字典元素以及使用递归。

Python3

# Python3 code to demonstrate working of 
# Remove K value items from dictionary nestings
# Using recursion + loop (For multiple nesting)
  
res = []
  
# helper function to solve problem
def hlper_fnc(test_dict):
    for key in test_dict:
        if type(test_dict[key]) == dict:
            hlper_fnc(test_dict[key])
        else:
            if test_dict[key] != K:
                res.append({key : test_dict[key]})
  
# initializing dictionary
test_dict = {"Gfg" : {"a" : 5, "b" : 8, "c" : 9},
             "is" : {"f" : 8, "l" : { "j" : 8, "k" : 10}},
             "Best" : {"i" : {"k" : { "o" : 8}}}}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 8
  
# computing result
hlper_fnc(test_dict)
  
# printing result 
print("The dictionary after value removal : " + str(res)) 
输出