Skip to main content
 首页 » 编程设计

python之字典数据未正确附加到另一个字典

2024年09月07日7kenshinobiy

词典数据未正确附加到另一个词典。这里的acc_grp是一个分组的pandas数据。

acc_grp

      amount_currency     balance    credit      debit     lid 
ldate                                                                
2018-04-01              0.0  -27359.250  30219.25  1115.0000  643259 
2018-04-02              0.0 -208574.742   5000.00  1194.0005  872275 

这里 template_dict 是我的词典。当我打印 result 时,我的 acc_grp 的两行都正确可用。

流(来自终端)

结果(第一次迭代)

{'date': '2018-04-01', 'credit': 30219.25, 'balance': -29104.25, 'debit': 1115.0} 

模板字典

{'code': u'300103', 'lines': [{'date': '2018-04-01', 'credit': 30219.25, 'balance': -29104.25, 'debit': 1115.0}], 'name': u'CASH COLLECTION'} 

在第一种情况下,result 正确附加到 template_dict。

结果(第 2 次迭代)

{'date': '2018-04-02', 'credit': 5000.0, 'balance': -3805.9994999999999, 'debit': 1194.0005} 

模板字典

{'code': u'300103', 'lines': [{'date': '2018-04-02', 'credit': 5000.0, 'balance': -3805.9994999999999, 'debit': 1194.0005}, {'date': '2018-04-02', 'credit': 5000.0, 'balance': -3805.9994999999999, 'debit': 1194.0005}], 'name': u'CASH COLLECTION'} 

这里我们看,template_dict的lines的值应该是result1,result2但数据以 result2,result2 的形式出现。

代码

                result = {} 
                template_dict = dict() 
                template_dict['lines'] = [] 
                template_dict['code'] = line['code'] 
                template_dict['name'] = line['name'] 
                for index,row in acc_grp.iterrows(): 
                    balance=0 
                    row.balance=row.debit.item()-row.credit.item() 
                    result['date']=row.name 
                    result['debit']=row.debit.item() 
                    result['credit']=row.credit.item() 
                    result['balance']=row.balance 
                    print result 
                    template_dict['lines'].append(result) 
                    print template_dict 

请您参考如下方法:

您需要为每一行创建一个新字典。否则,您总是在更改同一个字典:

            ... 
            for index,row in acc_grp.iterrows(): 
                result = {}  # Create a brand new dictionary 
                balance=0 
                row.balance=row.debit.item()-row.credit.item() 
                result['date']=row.name 
                ... 
                template_dict['lines'].append(result)