python - Merge list values inside a dictionary -



python - Merge list values inside a dictionary -

i have solve quite simple me in php, i'm missing how in python.

suppose have next dictionary:

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

all lists have same length, possible value of info be:

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

what i'm trying do:

when iterating list 'week' :

· if current week has same value next 1 in list:

·· overwrite week next one, overwrite year next one, , sum values same indexes week.

what expect obtain:

so result be:

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

what i've tried:

· iterating on dictionary, but poor knowledge of python, i've obtained errors such object of type 'bool' has no len() when trying build for loop. (i've used constructs for in range len(dictionary.index))

· checked out itertools , collections, i'm not able find suits.

· trying out in step-by step simple way: dumpling lists dictionary list , compare items 1 one, saving values list, etcetera.

any ideas or documentation check? (apart maintain learning python)

use itertools.groupby , iterate on enumerate(d['week']):

from itertools import groupby operator import itemgetter d = {'year': ['2014', '2014', '2014'], 'week': ['44', '49', '49'], 'value': [15, 20, 30]} out = {'year': [], 'week': [], 'value': []} k, g in groupby(enumerate(d['week']), key=itemgetter(1)): total = 0 i, x in g: total += d['value'][i] # `i` lastly index of grouping , `x` lastly week of group, # can utilize these values 'year' , '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']}

python list dictionary merge iteration

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -