Home > Net >  Dictonary wise subtraction
Dictonary wise subtraction

Time:11-02

I have two dictonaries in one dictonary:

d = {'A': {}, 'B': {}}

Where:

A = {'key1': [[3],[ ],[ ], [ ]], 'key2': [[1,2,3], [ ],[4,5,6],[]], 'key4:' ...}

So a Dictonary with a list of say length 4 (=n in the following), which has lists of other data in it at some points, which are not all the same length.

And B:

B = {'key1': [[ ],[ ], [ ], [ ]], 'key2': [[7,8,9], [ ],[10,11,12],[]], 'key4:' ...}

So the two are of the same length in terms of the content of the single keys and have the same naming of the keys. Now I want to subtract A from B, so that A[key1] with list of length n is subtracted element by element from B[key1] with list of length n, then key2 and so on.

New dictonary

C = {'key1':[Diff1,Diff2,Diff3,Diffn], 'key2': ...}

So that the diff is [ ] if there are not two numbers.

For key2 in the example therfore :

C = {...'key2': [[1-7,8-2,3-9],[ ], [4-10,5-11,6-12], []], ...}

(Of course calculate the difference and not display it)

Then a dictonary

D = {'key1': [mean(C['key1']), 'key2': mean(C['key2']),...} 

would have to be created, so the mean values of the C keys.

Unfortunately, I don't have that much experience with diconarys yet, so I would be grateful for any hint.

I wrote a code to average the values, however this way I skip the difference (which I need) and it also produces the warning for empty lists in the lists.

for key, value in d['A'].items():
        d['A'][key] = [(np.array(i).mean()) for i in value if not int(len(i)) ==0]

CodePudding user response:

I managed to obtain the difference by subtracting A from B and storing it into C by using the following code

for key, value in d['A'].items():
difference=[]
for i in range(len(d['A'][key])):
    outer=[]
    for j in range(len(d['A'][key][i])):
        outer.append(d['B'][key][i][j]-d['A'][key][i][j])
    difference.append(outer)
d['C'][key]=difference

Now this was the assumption dictionary I took from your question and used to test that it works

d={
'A' : {'key1': [[3],[2],[1], [5]], 'key2': [[1,2,3], [2],[4,5,6],[2]]},
'B' : {'key1': [[5],[ 1],[8], [9]], 'key2': [[2,3,11], [11],[8,2,22],[4]]},
'C':{}
}

And used a print statement to check the output. I guess you have got the mean part already figured out, hence leaving it with this much.

P.s: When the list element from A is empty, you get an empyty list as an output whereas when B is empty, It throws an error which can be handled using exception handling.

This is how you can handle the exception:

try:
   outer.append(d['B'][key][i][j]-d['A'][key][i][j])
except:
   outer.append([])
  • Related