Frage

I have two dictionaries where each value is a list of floats

d1 = {'a': [10,11,12], 'b': [9,10,11], 'c': [8,9,10], 'd': [7,8,9]}

d2 = {'a': [1,1,1], 'b': [2,3,2], 'c': [1,2,2], 'd': [4,3,4]}

I want to subtract the values between dictionaries d1-d2 and get the result:

d3 = {'a': [9,10,11], 'b': [7,7,9], 'c': [7,7,9], 'd': [3,5,5] }

I have found on this site entries on how to subtract dictionaries with only one float value per key, and how to subtract lists within each dictionary, but not between dictionaries.

Also, speed needs to be taken into account because I am going to run this ~200,000 times with different dictionaries each time.

War es hilfreich?

Lösung

Use a dict comprehension with

zip:

>>> {k:[x-y for x, y in zip(d1[k], d2[k])] for k in d1}
{'a': [9, 10, 11], 'c': [7, 7, 8], 'b': [7, 7, 9], 'd': [3, 5, 5]}

or map:

>>> from operator import sub
>>> {k:map(sub, d1[k], d2[k]) for k in d1}
{'a': [9, 10, 11], 'c': [7, 7, 8], 'b': [7, 7, 9], 'd': [3, 5, 5]}

Andere Tipps

If speed is important then you can try numpy:

import numpy as np

def sub(x, y):
    # probably it would be better if x and y already had numpy arrays as the values.
    return {key: np.array(x[key]) - np.array(y[key]) for key in x}

print sub(d1, d2)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top