我正在尝试解决一个问题,我需要根据某些条件区分两个字典中特定键的值,然后将结果存储在同一个字典中的新键中。下面提供了一个示例:
A = {'a':10,'b':abc,'c':''}
B = {'a':80,'b':def,'c':''}
C = {'a':20,'b':xyz,'c':''}
在检查键'b'的条件后,我需要使用键'c'的值更新字典B,使用字典A和B中键'a'的值的差值。我想要的输出应该如下所示:
Condition: the values of key 'b' should be 'abc' and 'def'.
B = {'a':80,'b':def,'c':70}
我使用了以下函数,但它引发了语法错误。
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
非常感谢任何形式的帮助。如果这个问题需要更多细节,请告诉我。
下面的回溯具有不同的文件名和属性。但附上供你参考。
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'
感谢。
答案 0 :(得分:1)
if A['b'] == 'abc' and B['b'] == 'def':
B['c'] = B['a'] - A['a']