【问题标题】:How to merge a nested list of dictionaries with other list of dictionaries?如何将嵌套的字典列表与其他字典列表合并?
【发布时间】:2021-04-26 02:31:12
【问题描述】:

我有一个包含字典列表的字典列表:

super_data: [{'data': [{'attributes': {'stuff': 'test'
                                       'stuff2': 'tester'}
                       }]}
             {'data': [{'attributes': {'stuff': 'test2'
                                       'stuff2': 'tester2'}
                       }]}

我还有其他字典列表,可能看起来像:

super_meta_data: [{'meta_data': [{'attributes': {'thing': 'testy'
                                                 'thing2': 'testy2'}
                                }]}
                  {'meta_data': [{'attributes': {'thing': 'testy3'
                                                 'thing': 'testy4'}
                                }]}

我想像这样合并嵌套的字典列表:

super_data: [{'data': [{'attributes': {'stuff': 'test'
                                       'stuff2': 'tester'}
                      }]
              'meta_data': [{'attributes': {'thing': 'testy'
                                            'thing2': 'testy2'}
                            }]
             }
             {'data': [{'attributes': {'stuff': 'test'
                                       'stuff2': 'tester'}
                      }]
              'meta_data': [{'attributes': {'thing': 'testy3'
                                            'thing2': 'testy4'}
                      }]
             }

我该怎么做呢?我正在尝试:

for i in super_data:
     super_data.append([i][super_meta_data]

但它正在抛出:

TypeError: 列表索引必须是整数或切片,而不是字典

欣赏任何见解!

【问题讨论】:

  • 请发布帮助者可以复制和粘贴的实际 Python 数据结构。让他们猜测和虚假输入是不体贴的。

标签: python json python-3.x python-2.7 dictionary


【解决方案1】:

您可以尝试以下操作,使用zip

for data, meta_data in zip(super_data, super_meta_data):
     data.update(meta_data)

或者,同样的结果,使用列表推导:

super_data = [{**d, **md} for d, md in zip(super_data, super_meta_data)]

>>> super_data
[{'data': [{'attributes': {'stuff': 'test', 'stuff2': 'tester'}}],
  'meta_data': [{'attributes': {'thing': 'testy', 'thing2': 'testy2'}}]},
 {'data': [{'attributes': {'stuff': 'test2', 'stuff2': 'tester2'}}],
  'meta_data': [{'attributes': {'thing': 'testy3', 'thing2': 'testy4'}}]}]

如果您想让基于索引的方法发挥作用:

for i in range(len(super_data)):
    super_data[i].update(super_meta_data[i])

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 2018-01-19
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多