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

标签 python python-3.x list-comprehension dictionary-comprehension

如果单个特定值在一个字典数组中匹配,如何将特定值合并到另一个字典数组中?

我有一组代表书籍的字典

books = [{'writer_id': '123-456-789', 'index': None, 'title': '黄雪'}, {'writer_id': '888-888-777' , 'index': None, 'title': 'Python for Dummies'}, {'writer_id': '999-121-223', 'index': 'Foo', 'title': '其他东西'}]

我有一组代表作者的字典

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与作者匹配作者id

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

books = [{'writer_id': '123-456-789', 'index': None, 'title': '黄雪', 'name': 'Pat'}, {'writer_id' : '888-888-777', 'index': None, 'title': 'Python傻瓜'}, {'writer_id': '999-121-223', 'index': 'Foo', 'title' : '别的东西', '名字': '五月'}]

我当前的解决方案是:

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 对于组合(合并、连接等)单独 DataFrame 的不同方式很有帮助。

关于python - 如果值匹配,则将一个字典数组中的特定值合并到另一个字典数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49265404/

相关文章:

python - Python中两种子串搜索方法的效率比较

python - 如何将csv文件写入特定文件夹

python - Matplotlib xtick 给出 "The truth value of an array with more than one element is ambiguous"

JavaScript,加密.subtle : how to import RSA private key?

python - python中的str性能

python - 如何大声朗读 Python 列表理解?

Python:为什么多个列表理解似乎比使用 if...elif 语句的单个 for 循环更快?

python - 如何抑制 Tensorflow (Python) 中的特定警告

python - 使用 try 和 except 创建复杂形式的字典

python - 任何人都可以帮助解决 TypeError : 'float' object is not callable' in following code