Skip to content
Advertisement

Calculate delta in dictionary of dictionary

I have a dictionary of dictionaries which hold list of tuples like this:

mydict:{'A1':{'week1': [(1,1,34),(1,2,3),(1,3,10),(2,1,3),(2,2,9)...()],
              'week2': [(1,1,4),(1,2,11),(1,3,8),(2,1,5),(2,2,7)...()],
               ...
              'week19': [(1,1,12),(1,2,13),(1,3,32),(2,1,45),(2,2,15)...()],
              'week20': [(1,1,43),(1,2,30),(1,3,6),(2,1,7),(2,2,4)...()]}
        'A2':{'week1': [(1,1,6),(1,2,4),(1,3,2),(2,1,87),(2,2,32)...()],
              'week2': [(1,1,32),(1,2,15),(1,3,43),(2,1,2),(2,2,12)...()],
               ...
              'week20': [(1,1,3),(1,2,3),(1,3,16),(2,1,17),(2,2,11)...()]}
               ...
 } 

I would like to calculate the delta of the third items (which their first two items are identical) in each tuple inside of the dictionaries, between each week (e.g., week1 and week2,.. week19 and week20)and put them as new dictionaries in the main dictionary. So my desired outcome could be like this:

    out_dict:{'A1':{'week1': [(1,1,34),(1,2,3),(1,3,10),(2,1,3),(2,2,9)...()],
              'week2': [(1,1,4),(1,2,11),(1,3,8),(2,1,5),(2,2,7)...()],
                ...
              'week19': [(1,1,12),(1,2,13),(1,3,32),(2,1,45),(2,2,15)...()],
              'week20': [(1,1,43),(1,2,30),(1,3,6),(2,1,7),(2,2,4)...()],
              'delta_wk1_wk2':[(1,1,30),(1,2, 8),(1,3,2),(2,1,2),(2,2,2)...()],
              'delta_wk20_wk19':[(1,1,31),(1,2, 23),(1,3,26),(2,1,38),(2,2,11)...()]
              ...
   }
        'A2':{'week1': [(1,1,6),(1,2,4),(1,3,2),(2,1,87),(2,2,32)...()],
              'week2': [(1,1,32),(1,2,15),(1,3,43),(2,1,2),(2,2,12)...()],
              ...
              'week19': [(1,1,7),(1,2,0),(1,3,2),(2,1,33),(2,2,10)...()],
              'week20': [(1,1,3),(1,2,3),(1,3,16),(2,1,17),(2,2,11)...()]}
               ...
              'delta_wk1_wk2':[(1,1,26),(1,2, 11),(1,3,41),(2,1,85),(2,2,20)...()],
              'delta_wk20_wk19':[(1,1,4),(1,2, 3),(1,3,14),(2,1,14),(2,2,1)...()]
 } 

Advertisement

Answer

To get each pair of weeks, you can use a pairwise iterator, which you can look at the itertools recipes to see the implementation; it looks like this:

from itertools import tee

def pairwise(iterable):
    x, y = tee(iterable)
    next(y, None)
    return zip(x, y)

Then you can use that on an entry of your dictionary:

def add_deltas(data):
    for first, second in pairwise(data.keys()):
        deltas = []
        for a, b in zip(data[first], data[second]):
            if b:
                deltas.append((a[0], a[1], abs(a[2] - b[2])))
        data[f'delta_{first}_{second}'] = deltas

Use this to loop through your dictionary:

for v in mydict.values():
    add_deltas(v)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement