合并字典中的列表值

时间:2014-10-23 10:25:49

标签: python list dictionary merge iteration

我必须在PHP中解决一些对我来说非常简单的事情,但是我很想知道如何在Python中使用它。

假设我有以下字典:

data = {'year': [], 'week': [], 'value': []}

所有列表的长度始终相同,因此数据的可能值为:

{'year': ['2014', '2014', '2014'], 'week': ['44', '49', '49'], 'value': [15, 20, 30]}

我正在尝试做什么:

迭代列表'周'时:

·如果当前周的值与列表中的下一个值相同:

··用下一个覆盖那一周,用下一个覆盖年份,并用与周相同的索引求和值。

我希望获得什么:

结果将是:

{'year': ['2014', '2014'], 'week': ['44', '49'], 'value': [15, 50]}

我尝试了什么:

·迭代字典,但是我对python知之甚少,在尝试构建object of type 'bool' has no len()循环时,我已经获得了诸如for之类的错误。 (我使用了构造for i in range len(dictionary.index)

·签出itertoolscollections,但我找不到合适的内容。

·以简单的方式逐步尝试:将字典中的列表转储到另一个列表中,然后逐个比较项目,将值保存到另一个列表中,等等。

要检查的任何想法或文档? (除了继续学习python)

1 个答案:

答案 0 :(得分:2)

使用itertools.groupby并迭代enumerate(d['week'])

from itertools import groupby
from operator import itemgetter

d = {'year': ['2014', '2014', '2014'], 'week': ['44', '49', '49'], 'value': [15, 20, 30]}
out = {'year': [], 'week': [], 'value': []}

for k, g in groupby(enumerate(d['week']), key=itemgetter(1)):
    total = 0
    for i, x in g:
        total += d['value'][i]
    # Now `i` is the last index of the group and `x` is the last week of the group,
    # We can use these to get values from 'year' and 'week'.
    out['year'].append(d['year'][i])
    out['week'].append(x)
    out['value'].append(total)

print out
#{'week': ['44', '49'], 'value': [15, 50], 'year': ['2014', '2014']}