如果值匹配,则将一个字典数组中的特定值合并到另一个数组中

Merge a specific value from one array of dicts into another if a value matches

如果一个特定值在它们之间匹配,我如何将一个特定值从一个字典数组合并到另一个字典数组?

我有一组表示书籍的字典

books = [{'writer_id': '123-456-789', 'index': None, 'title': 'Yellow Snow'}, {'writer_id': '888-888-777', 'index': None, 'title': 'Python for Dummies'}, {'writer_id': '999-121-223', 'index': 'Foo', 'title': 'Something Else'}]

我有一组代表作者的字典

authors = [{'roles': ['author'], 'profile_picture': None, 'author_id': '123-456-789', 'name': 'Pat'}, {'roles': ['author'], 'profile_picture': None, 'author_id': '999-121-223', 'name': 'May'}]

我想从 authors 中获取名字并将其添加到 books 中的字典中,其中书籍 writer_id 与作者 author_id 匹配。

理想情况下,我的最终结果是将书籍的字典数组更改为(注意第一个字典现在的值为 'name':'Pat',第二本书的值为 'name': 'May'):

books = [{'writer_id': '123-456-789', 'index': None, 'title': 'Yellow Snow', 'name': 'Pat'}, {'writer_id': '888-888-777', 'index': None, 'title': 'Python for Dummies'}, {'writer_id': '999-121-223', 'index': 'Foo', 'title': 'Something Else', 'name': 'May'}]

我目前的解决方案是:

for book in books:
  for author in authors:
    if book['writer_id'] == author['author_id']:
      book['author_name'] = author['name']

这行得通。然而,嵌套语句让我感到困扰并且觉得笨拙。我还有许多其他这样的结构,所以我最终得到了一个函数,其中有一堆类似的代码:

for book in books:
      for author in authors:
        if book['writer_id'] == author['author_id']:
          book['author_name'] = author['name']

books_with_foo = []
for book in books:
      for thing in things:
        if something:
          // do something


for blah in books_with_foo:
      for book_foo in otherthing:
        if blah['bar'] == stuff['baz']:
          // etc, etc.

或者,您如何将来自多个数据库表的数据聚合成一个东西...一些数据作为字典返回,一些作为字典数组返回?

Pandas 几乎肯定会在这里为您提供帮助。将您的字典转换为 DataFrames 以便于操作,然后合并它们:

import pandas as pd

authors = [{'roles': ['author'], 'profile_picture': None, 'author_id': '123-456-789', 'name': 'Pat'}, {'roles': ['author'], 'profile_picture': None, 'author_id': '999-121-223', 'name': 'May'}]
books = [{'writer_id': '123-456-789', 'index': None, 'title': 'Yellow Snow'}, {'writer_id': '888-888-777', 'index': None, 'title': 'Python for Dummies'}, {'writer_id': '999-121-223', 'index': 'Foo', 'title': 'Something Else'}]

df1 = pd.DataFrame.from_dict(books)
df2 = pd.DataFrame.from_dict(authors)

df1['author_id'] = df1.writer_id
df1 = df1.set_index('author_id')
df2 = df2.set_index('author_id')

result = pd.concat([df1, df2], axis=1)

您可能会发现 this page 有助于不同的组合方式(合并、串联等)分离 DataFrames