从字典 B 列表中通过唯一键减少字典 A 列表

问题描述

我正在尝试清理用户输入 new_accounts 并防止在数据库中存储重复项 db_accounts
目前我减少了 2 个步骤:获取唯一 ID 列表,然后通过该列表过滤用户输入

# tens of dicts each with tens of keys
new_accounts = [{'id':'wh4h3r'},{},{}]
# thousands of dicts
db_accounts = [{'id':'l5k6jy'},{}]

filterby = {a['id'] for a in db_accounts}
new_unique = [a for a in new_accounts if a['id'] not in filterby]

我想知道是否可以使用 itertools、functools、集合等进一步简化此代码

解决方法

如果您的最终目标是将 new_accounts 中的 id 添加到 db_accounts 中,同时避免重复,则此代码比您现有的代码稍微紧凑一些。

filtered_accounts = set(account["id"] for account in new_accounts) - set(account["id"] for account in db_accounts)
db_accounts.extend([{"id": id} for id in filtered_accounts])

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...