可散列容器,用于在每次迭代中保存百万个项目和修改

2024-06-16 11:49:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在处理的是一个由十几个条目组成的字典,经过几次迭代,这些条目会增长到上千万个字典条目。基本上,我的项目是由几个ID、值和特征定义的。我用从SQL服务器收集的JSON格式的数据创建dict。你知道吗

例如,我执行的操作是:

  • 以JSON格式获取SQL结果
  • 搜索“id1”和/或“id2”相同的项目
  • 通过求和float('value')合并具有相同“id1”的所有项

请看一个类似于我的dict的示例:

[
   {'id1':'01234-01234-01234',
    'value':'10',
    'category':'K'}
...
   {'id1':'01234-01234-01234',
    'value':'5',
    'category':'K'}
...
]

我想要的是:

[
...
   {'id1':'01234-01234-01234',
    'value':'15',
    'category':'K'}
...
]

我可以用dict of dicts来代替:

{
  '01234-01234-01234': {'value':'10',
                        'categorie':'K'}
...
  '01234-01234-01234': {'value':'5',
                        'categorie':'K'}
...
}

获得:

  {'01234-01234-01234': {'value':'15',
                        'categorie':'K'}
  ...
  }

我在Ram中有专用的4Go,在64位体系结构的字典中有数百万条字典,我想在时间和Ram中优化我的代码和操作。有没有比dictionary of dictionary更好的技巧或容器来实现这种操作?是创建一个新的对象来删除每次迭代的第一个对象,还是更改哈希对象本身更好?你知道吗

我使用的是python3.4。你知道吗

编辑:将问题简化为一个关于值的问题。 这个问题类似于How to sum dict elementsFastest way to merge n-dictionaries and add values on 2.6,但在我的例子中,我的dict中有string

EDIT2:目前,最好的性能是通过这种方法获得的:

def merge_similar_dict(input_list=list):
    i=0
    #sorted the dictionnary of exchanges with the id.
    try:
        merge_list = sorted(deepcopy(input_list), key=lambda k: k['id'])
        while (i+1)<=(len(merge_list)-1):
            while (merge_list[i]['id']==merge_list[i+1]['id']):
                merge_list[i]['amount'] = str(float(merge_list[i]['amount']) + float(merge_list[i+1]['amount']))
                merge_list.remove(merge_list[i+1])
                if i+1 >= len(merge_list):
                    break
                else:
                    pass
            i += 1
    except Exception as error:
        print('The merge of similar dict has failed')
        print(error)
        raise
        return merge_list
    return merge_list

当我的单子上有十几万条口述时,它开始变得很长(几分钟)。你知道吗


Tags: of项目对象id字典value条目merge