如何获取复杂字典的整数值

时间:2017-12-06 09:09:03

标签: openerp odoo-8

这里abc的值是一个整数,total是包含另一个词典的字典。但是当我运行这行时,

    total[div]['total_transport_allowance'] = abc

显示以下错误:"KeyError: None" 请帮忙

我想从这个陈述中得到的是将abc的值设为键'total_transport_allowance'

def print_excel_report(self,cr,uid,ids,data,context=None):
    result = self._get_lines(cr,uid,ids,data)
    filename= 'PayrollRegister.xls'
    workbook= xlwt.Workbook(encoding="UTF-8")
    sheet= workbook.add_sheet('Payroll Register',cell_overwrite_ok=True)
    style = xlwt.easyxf('font:height 400, bold True, name Arial; align: horiz center, vert center;borders: top medium,right medium,bottom medium,left medium')
    a = range(1,10)
    row = 1
    col =0
    header = ['Division','Basic','Transport Allowance']
    style2 = xlwt.easyxf('font: bold 1')
    total = {}

    for index,data in enumerate(result):
        div = data.get('Division',False)
        abc = data.get('transport_allowance',False) or 0

        if div:
            if div in total:
                total[div]['total_basic'] = total[div]['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] +  abc
            else:
                total[div] = {}
                total[div]['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc

        else:
            if 'Undefined' in total:
                total['Undefined']['total_basic'] = total['Undefined']['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] + abc

            else:
                total['Undefined'] = {}
                total['Undefined']['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc
        .......
        .....

4 个答案:

答案 0 :(得分:2)

试图拯救所有挫折中的东西:

你有一个if语句检查div的真实性。在假的情况下,然后使用div来访问总数。

即你有:

if div:
    # stuff
else:
    # stuff
    total[div]['total_transport_allowance'] = abc

由于总数没有关键div,所以这不起作用。

你需要像total[div] = {}

这样的东西

答案 1 :(得分:1)

您收到此错误是因为divNone

 if div:
    ....
    ....
 else:
    ...
    ...
    # div here is None or False ..
    # you cannot use it as key!!
    total[div]['total_transport_allowance'] = abc

您需要先在此处定义密钥。那么 如果div为None,你想放置abc。

修改

当我不在data.get('Division',False)时,我不知道div的价值是什么:

    div = data.get('Division', False)
    ...
    ...
    if div:
       .....
    else:
        # assing a value to div
        div = 'NEW_VALUE'
        # add dictionary there
        total[div] = {}
        if 'Undefined' in total:
            ....
        ...
        ...

答案 2 :(得分:1)

total[div]['total_transport_allowance'] = {}

这有效.. 我在

中做过这样的事情
total['Undefined']['total_transport_allowance'] = {}

也.. 谢谢大家的帮助

答案 3 :(得分:0)

KeyError is None表示未定义字典。 div是应该定义的字典。