Home > Mobile >  unzip nested dictionary in function to calculate dictionary values
unzip nested dictionary in function to calculate dictionary values

Time:11-12

I have different nested dictionaries, want to calculate discount wise score

A = {'tr_1': {'hos': 100.0, 'dy': 100.0},
 'tr_2': {'hos': 100.0, 'dy': 50.0},
 'tr_3': {'hos': 100.0, 'dy': 50.0}}

B = {'tr_1': {'cor': 160, 'ner': 0},
 'tr_2': {'cor': 69, 'ner': 36.14},
 'tr_3': {'cor': 63, 'ner': 41.69}}

c = {'tr_1': {'st': 0, 'st_c': 100.0},
 'tr_2': {'st': 1368, 'st_c': 0},
 'tr_3': {'st': 1366, 'st_c': 0}}

Below code is for single discount. I want to do this calculation for each trip want to save in another dictionary

dis = {}
A = {'dy':18}
B = {'ner':89}
C = {'st_c':56}
eff = (
        (20 * A['dy']) 
         
        (20 * B['ner']) 
         
        (20 * C['st_c'])
dis['value'] = eff

expected output like be:

dis = {'tr_1': {'eff':32},
'tr_2': {'eff':45},
'tr_3': {'eff':23}}

how to do that? Not required to multiply each nested dict in the last as you can see in the screenshot adding screenshot of expected but want in dict enter image description here

column eff be like

dd = {'tr1': {'eff':40},
'tr2':{'eff':360},
'tr3':{'eff':410}

CodePudding user response:

IIUC, you can try:

import math

dicts = [A, B, C]
keys = ['dy', 'ner', 'st_c']

out = {k: {'eff': round(0.2*math.prod(d[k][k2] for k2,d in zip(keys, dicts)), 2)}
       for k in A}

print(out)

Output:

{'tr_1': {'eff': 9.0},
 'tr_2': {'eff': 54.0},
 'tr_3': {'eff': 44.8}}

Used input:

A = {'tr_1': {'hos': 100.0, 'dy': 3},
     'tr_2': {'hos': 100.0, 'dy': 9},
     'tr_3': {'hos': 100.0, 'dy': 4}}

B = {'tr_1': {'cor': 160, 'ner': 5},
     'tr_2': {'cor': 69, 'ner': 6},
     'tr_3': {'cor': 63, 'ner': 8}}

C = {'tr_1': {'st': 0, 'st_c': 3},
     'tr_2': {'st': 1368, 'st_c': 5},
     'tr_3': {'st': 1366, 'st_c': 7}}
  • Related