【问题标题】:How to add an existing dictionary as a nested dictionary to an already existing dictionary in python?python - 如何将现有字典作为嵌套字典添加到python中已经存在的字典中?
【发布时间】:2020-07-12 22:34:03
【问题描述】:

在 python3 中,我有 2 个字典,dict1 和 dict2,它们都填充了键/值对。我想创建一个新字典 dict3 并将 dict1 和 dict2 作为嵌套字典添加到其中。我无法相信我浪费了多少时间试图用谷歌搜索解决方案。我在教程之后找到了关于如何从头开始创建嵌套字典的教程,但没有关于将现有字典添加到另一个字典的教程。

【问题讨论】:

  • 嵌套字典是什么意思?你想成为dict3的key是什么?

标签: python dictionary nested


【解决方案1】:

IIUC:

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

print(dict3)

输出:

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

或者如果你想添加两个字典:

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}}

另一种方式:

#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}}

【讨论】:

  • 非常感谢!这正是我一直没有得到的信息。我当然很欣赏不同的例子!
猜你喜欢
  • 2018-05-31
  • 2018-11-07
  • 1970-01-01
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2023-03-11
  • 2021-05-17
相关资源
最近更新 更多