【问题标题】:Append dictionaries in Python在 Python 中附加字典
【发布时间】:2013-07-12 16:54:03
【问题描述】:

我有两个来自 JSON 文件的字典,看起来像这样:

dict1 = {"data": [{"text": "text1", "id": "id1"}, {"text": "text2", "id": "id2"}]}
dict2 = {"data": [{"text": "text3", "id": "id3"}, {"text": "text4", "id": "id4"}]}

我想用它们创建以下内容:

dict = {"data": [{"text": "text1", "id": "id1"}, {"text": "text2", "id": "id2"}, {"text": "text3", "id": "id3"}, {"text": "text4", "id": "id4"}]}

我尝试了不同的方法,例如:

dict = dict1.update(dict2)

dict = dict1.append(dict2)

都错了。我认为问题出在我确实需要的“数据”部分。非常感谢您的帮助。谢谢。

【问题讨论】:

  • dict 不知道值是什么,那么他怎么会理解您要扩展列表? update 只是将一个字典的值替换为另一个字典中的值,而不执行任何其他操作。

标签: python dictionary append


【解决方案1】:
dict={"data": dict1["data"] +dict2["data"]}

【讨论】:

    【解决方案2】:

    updateappend 不对你的结构做任何假设,所以它们不能工作。您必须构建一个新字典:

    dict3 = {'data': [dict1['data'] + dict2['data']]}
    

    或者修改现有的之一:

    dict1['data'].extend(dict2['data'])
    

    【讨论】:

      【解决方案3】:

      不幸的是这样做:

      dict = dict1.update(dict2)
      

      您实际上替换data”键的值,因此您会收到不同的结果(值未合并)。

      试试这个:

      from itertools import chain
      
      your_dicts = [dict1, dict2]  # Whatever you need, eg. iterable with many dicts 
      result = {"data": list(chain.from_iterable(d['data'] for d in your_dicts))}
      

      这将适用于许多字典,甚至是遍历它们的迭代器。它不需要您在创建字典时明确列出它们。

      证明:http://ideone.com/V1HHNR

      【讨论】:

        猜你喜欢
        • 2016-10-14
        • 1970-01-01
        • 1970-01-01
        • 2021-05-08
        • 2019-03-14
        • 2020-12-06
        • 1970-01-01
        • 2016-12-30
        • 2012-09-26
        相关资源
        最近更新 更多