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

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

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

在第一种情况下,结果正确附加到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

最佳答案

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

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

关于python - 字典数据未正确附加到另一个字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50147967/

相关文章:

javascript - 从 Javascript 确定 Django 用户 ID

python 使用 bool 表达式通过 While 循环遍历列表的元素

python-2.7 - 导入错误 : cannot import name RequestSite when inlude 'registration' in installed apps

Python 用空格分割字符串,除非 a\在前面

python - Numpy.minimum 与 Pandas.Series 时间戳类型错误 : Cannot compare 'Timestamp' with 'int'

python - 用 python 和 pandas 传输和写入 Parquet 得到时间戳错误

python - 遍历多个文件的所有行的最 pythonic 方法是什么?

python - Django:Twitter 登录被重定向到示例域

python - 两列 CSV 数据排序 - 一列 str(升序),另一列 date(降序)

python - 如何使用 iloc 将条件语句应用于 Pandas Dataframe 上的多个列?