求和字典列表的值

时间:2016-05-23 15:39:09

标签: python list python-2.7 dictionary

我有这个词典列表:

[{'Total Incidents': '1', 'CrimeDate': '05/14/2016'}, {'Total Incidents': '1', 'CrimeDate': '05/14/2016'}, {'Total Incidents': '1', 'CrimeDate': '05/14/2016'}, {'Total Incidents': '1', 'CrimeDate': '05/14/2016'}, {'Total Incidents': '1', 'CrimeDate': '05/14/2016'}, {'Total Incidents': '1', 'CrimeDate': '05/14/2016'}, {'Total Incidents': '1', 'CrimeDate': '05/14/2016'}, {'Total Incidents': '1', 'CrimeDate': '05/14/2016'}, {'Total Incidents': '1', 'CrimeDate': '05/14/2016'}]

我需要将'Total Incidents'的de值转换为int,并将它们相加。此外,如果日期相同,则该函数将获取所有日期并将其转换为一个日期。例如,输出应该是这样的:

[{'Total Incidents': 9, 'CrimeDate':'05/14/2016'}]

这是我到目前为止所尝试的:

dictf = reduce(lambda x, y: dict((k, v + y[k]) for k, v in x.iteritems()), dict1)

dict1是包含第一个字典的变量。 但是输出不是我想要的,它给了我这个:

{'Total Incidents': '111111111', 'CrimeDate': '05/14/201605/14/201605/14/201605/14/201605/14/201605/14/201605/14/201605/14/201605/14/2016'}

提前致谢

1 个答案:

答案 0 :(得分:3)

使用itertools.groupby

>>> [{'CrimeDate': g[0], 'Total Incidents': sum(map(lambda x: int(x['Total Incidents']), g[1]))} for g in itertools.groupby(d, lambda x: x['CrimeDate'])]
[{'Total Incidents': 9, 'CrimeDate': '05/14/2016'}]