subract two nested dictionaries python

Question:

i have two nested dict

{'BTC': {'DAE': -10526, 'Vega': 186, 'Theta': -34, 'Gamma': 149674},
 'ETH': {'DAE': -1123, 'Vega': 57, 'Theta': -5, 'Gamma': 2257}}

and

{'BTC': {'DAE': -105126, 'Vega': 1186, 'Theta': -314, 'Gamma': 1419674},
 'ETH': {'DAE': -11213, 'Vega': 157, 'Theta': -15, 'Gamma': 22157}}

Want to get subracted dict values. Getting the same with for loop. but any other way other than forloop.

Asked By: Madan

||

Answers:

Assuming you want d1 - d2.

You can use a dictionary comprehension:

out = {k1: {k2: v2-d2[k1][k2] for k2,v2 in v1.items()} for k1, v1 in d1.items()}

And if there is a chance that not all values are present in d2:

out = {k1: {k2: v2-d2.get(k1, {}).get(k2, 0) for k2,v2 in v1.items()}
       for k1, v1 in d1.items()}

Or with :

import pandas as pd
out = pd.DataFrame(d1).sub(pd.DataFrame(d2)).to_dict()

Output:

{'BTC': {'DAE': 94600, 'Vega': -1000, 'Theta': 280, 'Gamma': -1270000},
 'ETH': {'DAE': 10090, 'Vega': -100, 'Theta': 10, 'Gamma': -19900}}

Reproducible input:

d1 = {'BTC': {'DAE': -10526, 'Vega': 186, 'Theta': -34, 'Gamma': 149674},
      'ETH': {'DAE': -1123, 'Vega': 57, 'Theta': -5, 'Gamma': 2257}}

d2 = {'BTC': {'DAE': -105126, 'Vega': 1186, 'Theta': -314, 'Gamma': 1419674},
      'ETH': {'DAE': -11213, 'Vega': 157, 'Theta': -15, 'Gamma': 22157}}
Answered By: mozway