如果单个特定值在一个字典数组中匹配,如何将特定值合并到另一个字典数组中?
我有一组代表书籍的字典
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/