You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于linkhash去重多pickle字典并重新dump的技术问询

基于'linkhash'键去重字典并重新保存的实现方法

步骤1:加载已保存的字典列表

假设你已经通过pickle.load加载了包含多个字典的列表,以下是标准加载代码:

import pickle

# 替换为你的文件路径
with open('original_data.pkl', 'rb') as input_file:
    dict_list = pickle.load(input_file)

步骤2:按'linkhash'键去重

利用集合(Set)快速跟踪已出现的linkhash值,遍历字典列表并筛选出唯一条目:

seen_linkhashes = set()
unique_dict_list = []

for item in dict_list:
    # 获取当前字典的linkhash值
    current_linkhash = item.get('linkhash')
    
    # 仅保留未出现过的linkhash对应的字典
    if current_linkhash is not None and current_linkhash not in seen_linkhashes:
        seen_linkhashes.add(current_linkhash)
        unique_dict_list.append(item)

说明:

  • 使用集合的in操作是O(1)时间复杂度,比列表查找更高效,适合处理大量数据。
  • 加入current_linkhash is not None的判断,避免部分字典缺失linkhash键导致的异常。

步骤3:保存去重后的结果

将去重后的字典列表重新写入文件:

# 替换为你想要保存的文件路径
with open('deduplicated_data.pkl', 'wb') as output_file:
    pickle.dump(unique_dict_list, output_file)

完整示例

假设你的示例字典如下:

sample_dicts = [
    {'linkhash': 'abc123', 'content': 'foo'},
    {'linkhash': 'def456', 'content': 'bar'},
    {'linkhash': 'abc123', 'content': 'duplicate foo'},
    {'linkhash': 'ghi789', 'content': 'baz'}
]

运行上述代码后,unique_dict_list将只保留abc123、def456、ghi789对应的三个字典,重复的abc123条目会被移除。

内容的提问来源于stack exchange,提问作者Rainer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 17:02:08