简体   繁体   English

如何将现有字典作为嵌套字典添加到 python 中的现有字典中?

[英]How to add an existing dictionary as a nested dictionary to an already existing dictionary in python?

In python3, I have 2 dictionaries, dict1 and dict2 that are both populated with key/value pairs.在 python3 中,我有 2 个字典,dict1 和 dict2,它们都填充了键/值对。 I want to create a new dictionary dict3 and add both dict1 and dict2 as nested dictionaries to it.我想创建一个新字典 dict3 并将 dict1 和 dict2 作为嵌套字典添加到它。 I cant BELIEVE how much time Ive wasted trying to google a solution.我无法相信我浪费了多少时间试图用谷歌搜索解决方案。 I find tutorial after tutorial about how to create nested dictionaries from scratch but nothing about adding an existing dictionary nested to another dictionary.我在教程之后找到有关如何从头开始创建嵌套词典的教程,但没有关于将现有词典添加到另一个词典的教程。

IIUC:国际大学联盟:

dict1={1:2,3:4}
dict2={5:6,7:8}
dict3=dict(list(dict1.items())+[('dict2', dict2)])

print(dict3)

Output: Output:

{1: 2, 3: 4, 'dict2': {5: 6, 7: 8}}

Or if you want to add the two dictionary:或者如果你想添加两个字典:

dict1={1:2,3:4}
dict2={5:6,7:8}
dict3=dict([('dict1', dict1)]+[('dict2', dict2)])

print(dict3)
#Output:
#{'dict1': {1: 2, 3: 4}, 'dict2': {5: 6, 7: 8}}

Another ways:另一种方式:

#first scenario
dict1={1:2,3:4}
dict2={5:6,7:8}
dict3={**dict1}
dict3.update({'dict2':dict2})
print(dict3)
#Output:
#{1: 2, 3: 4, 'dict2': {5: 6, 7: 8}}

#second scenario
dict1={1:2,3:4}
dict2={5:6,7:8}
dict3={}
dict3.update({'dict1':dict1,'dict2':dict2})
print(dict3)
#Output:
#{'dict1': {1: 2, 3: 4}, 'dict2': {5: 6, 7: 8}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM