如何将字典中一个键的两个值之间的差异存储到另一个新键中?

2024-05-18 23:40:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试解决一个问题,在这个问题中,我需要根据某些条件在两个字典中获取特定键的值之间的差异,然后将结果存储在同一个字典中的一个新键中。下面提供了一个示例:

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'

谢谢。你知道吗


Tags: csvtoinpydictionary字典defline

热门问题