根据关键字将列表中的项目添加到现有字典中 [英] adding items from list to existing dictionary based on key

查看:56
本文介绍了根据关键字将列表中的项目添加到现有字典中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这本词典,它使用 id_num 作为键

Say I have this dictionary that uses a id_num as a key

{1665845 : Person(1665845, stuff)} {1294919 : Person(1294919, stuff)}

我还有另一个列表,其中包含[Id_num,日期,数据....]计数。

And I have another list that has lists containing [Id_num, date, data.....] counts.

[[['1665845', '2001-01-06', '28,448,615,27,705'], ['1294919', '2001-01-04', '639,118,328,413,222,491,738,389,11,372,183,650,281,643,26,398,685,171'], ['1294919', '2001-01-03', '771,373']]]

我如何总结所有属于id_num并将其添加为字典中的新项

How can I sum up all the data belonging to the id_num and add it as a new item in the dictionary

{1294919 : Person(1294919, stuff, sum)}


推荐答案

看起来您可以通过collections.defaultdict

Looks like you can achieve this by collections.defaultdict

person_dict = {1665845 : Person(1665845,  stuff), 1294919 : Person(1294919, stuff)}  # existing dictionary
l = [['1665845', '2001-01-06', '28,448,615,27,705'], ['1665845', '2001-01-10', '218,37,356,621,466,319,147,774,231,167,399,150,417,34,3'], ['1294919', '2001-01-04', '639,118,328,413,222,491,738,389,11,372,183,650,281,643,26,398,685,171'], ['1294919', '2001-01-10', '314,611,485,208,515,240,586,511,713,58,28,392,140,529,353,489,375,412,596'], ['1665845', '2001-01-04', '670,665,681,184,22,752,390,523,507,171,467,19,296,720,58,230,721,686'], ['1665845', '2001-01-02', '432,210,732,204,771,555,448,82,343'], ['1294919', '2001-01-06', '113,225,564,554,392,544,313'], ['1294919', '2001-01-05', '437,219,239,545,588,303,477,384,87,254,429,635,188,372,572,712,383'], ['1294919', '2001-01-03', '771,373'], ['1294919', '2001-01-08', '650,679,492,524,202,689,224,268,195,455,400,235,518,505']]

from collections import defaultdict
d_dict = defaultdict(int)
for k,_,v in l:
    d_dict[int(k)]+=sum(int(i) for i in v.split(','))
#dict(d_dict)
#{1294919: 31022, 1665845: 17701} 

for k in person_dict:
    person_dict[k] = Person(k, stuff, d_dict[k])

这篇关于根据关键字将列表中的项目添加到现有字典中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆