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

Python 字典数据未正确附加到另一个字典,python,python-2.7,pandas,odoo-10,pandas-groupby,Python,Python 2.7,Pandas,Odoo 10,Pandas Groupby,字典数据未正确附加到另一个字典。这里的acc\u grp是一个分组数据 acc\U grp amount_currency balance credit debit lid ldate 2018-04-01 0.0 -27359.250 30219.25 1115.0000 643259 201

字典数据未正确附加到另一个字典。这里的
acc\u grp
是一个分组数据

acc\U 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\u dict
是我的字典。当我打印
result
时,我的
acc\u grp
的两行都正确可用

流量(从终端)

结果(第一次迭代)

模板内容

{'code': u'300103', 'lines': [{'date': '2018-04-01', 'credit': 30219.25, 'balance': -29104.25, 'debit': 1115.0}], 'name': u'CASH COLLECTION'}
{'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'}
在第一种情况下,
结果
被正确地附加到
模板_dict

结果(第二次迭代)

模板内容

{'code': u'300103', 'lines': [{'date': '2018-04-01', 'credit': 30219.25, 'balance': -29104.25, 'debit': 1115.0}], 'name': u'CASH COLLECTION'}
{'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\u dict
的值应该是
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)