首页 > 解决方案 > 如何在 Python 中搜索“dict”对象中的值组合

问题描述

我正在尝试根据另一个列表更新/附加字典项目列表。

父列表

{'date': '2019-03-07', 'start_time': '2019-03-07 10:08:21', 'duration': '5'}     
{'date': '2019-03-07', 'start_time': '2019-03-07 10:14:43', 'duration': '15'}
{'date': '2019-03-07', 'start_time': '2019-03-07 10:31:22', 'duration': '13'}

新列表

{'date': '2019-03-07', 'start_time': '2019-03-07 10:08:21', 'duration': '5'}     
{'date': '2019-03-07', 'start_time': '2019-03-07 10:14:43', 'duration': '15'}
{'date': '2019-03-09', 'start_time': '2019-03-09 10:31:22', 'duration': '13'}
{'date': '2019-03-10', 'start_time': '2019-03-10 10:31:22', 'duration': '13'}
{'date': '2019-03-11', 'start_time': '2019-03-11 10:31:22', 'duration': '13'}
{'date': '2019-03-12', 'start_time': '2019-03-12 10:31:22', 'duration': '13'}

我想用NewList中的新项目更新ParentList。如您所见,后者的前两项在前者中重复。所以我只想将最后 4 个项目(来自NewList)添加到ParentList中。

简单的方法是遍历每个NewList项目并检查它是否已经存在于ParentList中。

代码

for newItem in NewList:
    bln_item_exists = False
    for parentItem in ParentList:
        if dict(newItem).get("date") == dict(parentItem).get("date") and dict(newItem).get("start_time") == dict(parentItem).get("start_time"):
            bln_item_exists = True
            break
    if not bln_item_exists:
        items_to_append.append(newItem)

我担心随着我的数据库大小增加,性能会受到影响,有没有更有效的方法来做同样的事情?

标签: python-3.xdictionary

解决方案


对于这些类型的操作,我建议使用pandas

import pandas as pd

df1 = pd.DataFrame(ParentList)
df2 = pd.DataFrame(NewList)
df3 = pd.concat([df1,df2])
df3.drop_duplicates(subset=['date', 'start_time'], inplace=True, keep='last')

推荐阅读