【问题标题】:How append multiple dicto into a one dict python如何将多个字典附加到一个字典 python
【发布时间】:2021-06-12 02:39:18
【问题描述】:

我使用 python 开发,并且我有多个字典,例如:

Dict1: {‘hi’:’340’, ‘hello’:’570’, ’me’:´800’}
Dict1: {‘hi’:’200’, ‘hello’:’100’, ’me’:´389’}

我想将它们一起添加到一个字典中:

Dict_new= { {‘hi’:’340’,‘hello’:’570’, ’me’:´800’},     {‘hi’:’200’, ‘hello’:’100’, ’me’:´389’}} 

最后我希望得到这个输出:

 {‘elements’:{{‘hi’:’340’,‘hello’:’570’, 
                    ’me’:´800’},
                 {‘hi’:’200’, ‘hello’:’100’, 
                ’me’:´389’}}}

那么最好的方法是什么?

【问题讨论】:

  • 也许让它成为一个字典列表而不是字典的字典。
  • 你想mergedicts吗?您不能将字典添加到另一个字典,因为它们不是 hashable type

标签: python python-3.x dictionary data-science


【解决方案1】:

不要使用set,请考虑使用一个列表来存储您的字典。

newDict = {}
newDict['element'] = [dict1,dict2]

输出

{'elements': [{'hi': '340', 'hello': '570', 'me': '800'}, {'hi': '200', 'hello': '100', 'me': '389'}]}

【讨论】:

  • 感谢您的回答,我已经使用列表来存储我所有的字典,但我想将它们存储在字典而不是列表中。
  • @Brun 这不是一个字典。那是一套。
猜你喜欢
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 2019-02-25
  • 2023-02-24
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
相关资源
最近更新 更多