Python – 删除无嵌套记录
有时,在使用Python Records 时,可能会遇到问题,我们需要删除嵌套记录中所有键值都为 None 的数据。这类问题可以应用于数据预处理。让我们讨论可以执行此任务的某些方式。
方法 #1:使用all()
+ 字典理解
上述功能的组合可以用来解决这个问题。在这种情况下,使用 all() 完成字典重构中不包含所有 None 值的所有值的删除。
# Python3 code to demonstrate working of
# Remove None Nested Records
# Using all() + dictionary comprehension
# initializing dictionary
test_dict = {'gfg' : {'a' : 1, 'b' : 2},
'is' : {'d' : None, 'e' : None},
'best' : {'g' : 1}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Remove None Nested Records
# Using all() + dictionary comprehension
res = {key: sub1 for key, sub1 in test_dict.items() if not
all(sub2 is None for sub2 in sub1.values())}
# printing result
print("The dictionary after removal : " + str(res))
输出 :
The original dictionary is : {‘gfg’: {‘b’: 2, ‘a’: 1}, ‘is’: {‘e’: None, ‘d’: None}, ‘best’: {‘g’: 1}}
The dictionary after removal : {‘gfg’: {‘b’: 2, ‘a’: 1}, ‘best’: {‘g’: 1}}
方法 #2:使用any()
+ 字典理解
上述功能的组合也可以用来解决这个问题。在此,我们使用 any() 将所有具有任何键的记录保留为非无键。
# Python3 code to demonstrate working of
# Remove None Nested Records
# Using any() + dictionary comprehension
# initializing dictionary
test_dict = {'gfg' : {'a' : 1, 'b' : 2},
'is' : {'d' : None, 'e' : None},
'best' : {'g' : 1}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Remove None Nested Records
# Using any() + dictionary comprehension
res = {key: sub1 for key, sub1 in test_dict.items() if
any(sub2 is not None for sub2 in sub1.values())}
# printing result
print("The dictionary after removal : " + str(res))
输出 :
The original dictionary is : {‘gfg’: {‘b’: 2, ‘a’: 1}, ‘is’: {‘e’: None, ‘d’: None}, ‘best’: {‘g’: 1}}
The dictionary after removal : {‘gfg’: {‘b’: 2, ‘a’: 1}, ‘best’: {‘g’: 1}}