【问题标题】:Dictionary data is not properly appended to another dictionay字典数据未正确附加到另一个字典
【发布时间】:2018-10-13 08:24:00
【问题描述】:

字典数据未正确附加到另一个字典。这里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}

template_dict

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

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

结果(第二次迭代)

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

template_dict

{'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_dictlines 的值应该是 result1result2 但数据是 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

【问题讨论】:

    标签: python python-2.7 pandas odoo-10 pandas-groupby


    【解决方案1】:

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

                ...
                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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-18
      • 2018-07-27
      • 2023-02-24
      • 2022-06-17
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多