Mohit Sharma
Mohit Sharma

Reputation: 189

How to take difference between two values of a key in dictionary and store it in another new key?

I am trying to solve a problem where I need to take difference between values of a particular key in two dictionary based on some conditions and then store the result in a new key in the same dictionary. A sample is provided below:

A = {'a':10,'b':abc,'c':''}
B = {'a':80,'b':def,'c':''}
C = {'a':20,'b':xyz,'c':''}

After checking the condition for key 'b', I need to update dictionary B with its value of key 'c' with the difference of values of key 'a' in dictionaries A and B. My desired output should look like:

 Condition: the values of key 'b' should be 'abc' and 'def'. 

B = {'a':80,'b':def,'c':70}

I used below function but it threw syntax error.

dict2 = {'d':''}
for dic in dictionary:
   dic.update(dict2)

def func(dictionary):
 for dic in dictionary:
      if dic['b'] == 'def':
          if dic['b'] == 'abc':
              dic['d'] = dic['b']
      dic['c'] = dic['a'].subtract(dic['d'])
 return dictionary

Any kind of help is highly appreciated. Let me know if more details are required on this question.

The traceback below has different file names and attributes. But attaching for your reference.

Traceback (most recent call last):

  File "<ipython-input-12-3d57363f374c>", line 1, in <module>
runfile('C:/Users/msharma/Desktop/Python CSV files/Notification to Chargeback.py', wdir='C:/Users/msharma/Desktop/Python CSV files')

  File "C:\Users\msharma\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
execfile(filename, namespace)

  File "C:\Users\msharma\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/msharma/Desktop/Python CSV files/Notification to Chargeback.py", line 69, in <module>
not_to_chb(dicts)

  File "C:/Users/msharma/Desktop/Python CSV files/Notification to Chargeback.py", line 66, in not_to_chb
dic['Conversion Period'] = dic['of Difference in week'].subtract(dic['Week of NotificationOfFraud'])

AttributeError: 'float' object has no attribute 'subtract'

Thanks.

Upvotes: 0

Views: 113

Answers (1)

JCVanHamme
JCVanHamme

Reputation: 1050

if A['b'] == 'abc' and B['b'] == 'def':
    B['c'] = B['a'] - A['a']

Upvotes: 1

Related Questions