Python - 把扁平化字典转换成嵌套字典


Python 字典包含键和值。如果我们有两个或更多个要合并为嵌套字典的字典,那么我们可以采用以下方法。这里,字典给出带有新键,这些新键将成为嵌套字典中的键。

分配键

在此方法中,我们将创建一个新的空字典。然后,将给定的字典分别分配给每个新键。结果字典将是带有分配的键的嵌套字典。

示例

dictA = {'Sun': 1, 'Mon': 2}
dictB = {'Tue': 3, 'Sun': 5}

# Given Dictionaries
print("DictA : ",dictA)
print("DictB: ",dictB)

# Using key access and dict()
res = dict()
res['Netsed_dict_1'] = dictA
res['Netsed_dict_2'] = dictB

# printing result
print("Netsed Dictionary: \n" ,res)

运行上述代码会给出以下结果 −

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

DictA : {'Sun': 1, 'Mon': 2}
DictB: {'Tue': 3, 'Sun': 5}
Netsed Dictionary:
{'Netsed_dict_1': {'Sun': 1, 'Mon': 2}, 'Netsed_dict_2': {'Tue': 3, 'Sun': 5}}

使用 zip

zip 函数可以将键和字典转换为元组。然后,我们应用 dict 函数以获得最终结果,这是一个包含新键和输入字典的字典。

示例

dictA = {'Sun': 1, 'Mon': 2}
dictB = {'Tue': 3, 'Sun': 5}

# Given Dictionaries
print("DictA : ",dictA)
print("DictB: ",dictB)

# Using zip
dict_keys = ['Netsed_dict_1','Netsed_dict_2']
all_dicts = [dictA,dictB]
res = dict(zip(dict_keys,all_dicts))
# printing result
print("Netsed Dictionary: \n" ,res)

运行上述代码会给出以下结果 −

输出

DictA : {'Sun': 1, 'Mon': 2}
DictB: {'Tue': 3, 'Sun': 5}
Netsed Dictionary:
{'Netsed_dict_1': {'Sun': 1, 'Mon': 2}, 'Netsed_dict_2': {'Tue': 3, 'Sun': 5}}

更新于: 2020-12-28

619 次查看

开启你的职业生涯

通过完成课程获得认证

开始
广告