Python - 从字典中删除顶级
有时,在使用Python字典时,我们可以嵌套字典,每个键都是单值字典。在此我们需要删除顶级字典。这可以应用于数据预处理。让我们讨论可以执行此任务的某些方式。
方法 #1:使用values()
+ 字典理解
上述功能的组合可以用来解决这个问题。在此,我们使用字典理解执行字典重建任务,并使用 values() 提取嵌套列表。
# Python3 code to demonstrate working of
# Remove Top level from Dictionary
# Using dictionary comprehension + values()
# initializing dictionary
test_dict = {'gfg' : {'data1' : [4, 5, 6, 7]},
'is' : {'data2' : [1, 3, 8]},
'best' : {'data3' : [9, 10, 13]}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Remove Top level from Dictionary
# Using dictionary comprehension + values()
res = dict(ele for sub in test_dict.values() for ele in sub.items())
# printing result
print("The top level removed dictionary is : " + str(res))
The original dictionary is : {‘is’: {‘data2’: [1, 3, 8]}, ‘gfg’: {‘data1’: [4, 5, 6, 7]}, ‘best’: {‘data3’: [9, 10, 13]}}
The top level removed dictionary is : {‘data1’: [4, 5, 6, 7], ‘data2’: [1, 3, 8], ‘data3’: [9, 10, 13]}
方法 #2:使用ChainMap() + dict()
上述功能的组合也可以用来解决这个问题。在此,我们使用 ChainMap() 来执行嵌套值的映射。
# Python3 code to demonstrate working of
# Remove Top level from Dictionary
# Using ChainMap() + dict()
from collections import ChainMap
# initializing dictionary
test_dict = {'gfg' : {'data1' : [4, 5, 6, 7]},
'is' : {'data2' : [1, 3, 8]},
'best' : {'data3' : [9, 10, 13]}}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Remove Top level from Dictionary
# Using ChainMap() + dict()
res = dict(ChainMap(*test_dict.values()))
# printing result
print("The top level removed dictionary is : " + str(res))
The original dictionary is : {‘is’: {‘data2’: [1, 3, 8]}, ‘gfg’: {‘data1’: [4, 5, 6, 7]}, ‘best’: {‘data3’: [9, 10, 13]}}
The top level removed dictionary is : {‘data1’: [4, 5, 6, 7], ‘data2’: [1, 3, 8], ‘data3’: [9, 10, 13]}