繁体   English   中英

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

[英]Reducing list of dicts A by unique key from list of dicts B

我正在尝试清理用户输入new_accounts并防止在 DB 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、collections 等进一步简化此代码?

如果您的最终目标是在避免重复的同时将db_accounts new_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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM