Python – 删除嵌套的无字典
有时,在使用记录时,我们可能会遇到需要从字典中删除空的嵌套记录的问题。这可以应用于数据预处理。让我们讨论可以执行此任务的某些方式。
方法 #1:使用dict() + filter()
这是可以执行此任务的方式之一。在此,我们使用 filter() 执行过滤 None 值的任务。
# Python3 code to demonstrate working of
# Removing Nested None Dictionaries
# Using filter() + dict()
# initializing dictionary
test_dict = {'gfg' : {'a': 5}, 'best' : {}, 'for' : {}, 'geeks' : {'b' : 6}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Removing Nested None Dictionaries
# Using filter() + dict()
res = dict(filter(lambda sub: sub[1], test_dict.items()))
# printing result
print("The dictionary after filtering is : " + str(res))
输出 :
The original dictionary is : {‘geeks’: {‘b’: 6}, ‘for’: {}, ‘gfg’: {‘a’: 5}, ‘best’: {}}
The dictionary after filtering is : {‘geeks’: {‘b’: 6}, ‘gfg’: {‘a’: 5}}
方法#2:使用字典理解
这是可以执行此任务的方式之一。在此我们只是通过检查键的值存在来重新创建字典。
# Python3 code to demonstrate working of
# Removing Nested None Dictionaries
# Using dictionary comprehension
# initializing dictionary
test_dict = {'gfg' : {'a': 5}, 'best' : {}, 'for' : {}, 'geeks' : {'b' : 6}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Removing Nested None Dictionaries
# Using dictionary comprehension
res = {key : val for key, val in test_dict.items() if val}
# printing result
print("The dictionary after filtering is : " + str(res))
输出 :
The original dictionary is : {‘geeks’: {‘b’: 6}, ‘for’: {}, ‘gfg’: {‘a’: 5}, ‘best’: {}}
The dictionary after filtering is : {‘geeks’: {‘b’: 6}, ‘gfg’: {‘a’: 5}}