如何将嵌套的字典列表与其他字典列表合并?

How to merge a nested list of dictionaries with other list of dictionaries?

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

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: list indices must be integers or slices, not dict

感谢任何见解!

您可以尝试以下方法,使用 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])