为什么python词典给我Keyerror?

时间:2014-03-17 09:51:49

标签: python

我正在使用文件a.py中的以下代码阅读excel文件并创建字典。

productNo = int(worksheet.cell_value(curr_row, 1))
    print "Product No :" + str(productNo)
    products[productNo] = {}

    while curr_cell < num_cells:
        curr_cell += 1
        header =  str(worksheet.cell_value(0, curr_cell))


        # Cell Types: 0=Empty, 1=Text, 2=Number, 3=Date, 4=Boolean, 5=Error, 6=Blank
        cell_type = worksheet.cell_type(curr_row, curr_cell)
        #print '    ',curr_cell,' <-> ', cell_type
        cell_value = worksheet.cell_value(curr_row, curr_cell)
        if cell_type == 0 or cell_type == 6:
            products[productNo][header] = ""
        if cell_type == 1:
            #products[productNo] = {header :cell_value}
            products[productNo][header] = cell_value
        elif cell_type == 2:
            cell_value = int(cell_value)
            print "Header " + header
            products[productNo][header] = cell_value
        elif cell_type == 3:
            products[productNo] = {header :cell_value}
        elif cell_type == 4:
            products[productNo] = {header :cell_value}

在文件main.py中,我通过将变量产品作为字典传递来调用上面编写的代码(在函数中)和catalouge.readExcel(&#39; D:/Personal/CatalogNo_1134.xls',products)。

转储它时,我得到所有的键和值。

print "Dump " + str(products)

    print  products.keys()

    print products['28852']['ProductNo']
    print products['28852']['Style']


Dump {28852: {'Category': u'Party Wear', 'Style': u'Designer', 'ProductNo': 28852, 'ProductGroup': u'Salwar Kameez', 'CatalogNo': 1134, 'ProductType': u'Salwar Kameez', 'SubCategoryDefinition': '', 'Fabric': u'Faux Georgette', 'MinWebPrice': 3395, 'Description': u'Capture The Exuberance Of Womanhood In Its Full Glory That Will Bring Out Your Fragility And Femininity. Genuine Magnificence Will Come Out Through The Dressing Style With This Off White Faux Georgette Salwar Kameez. The Appealing Lace|Resham Work Through The Attire Is Awe-Inspiring.', 'OptionOfSleeves': '', 'Rate/FreeSize': 2095, 'XLRate': 0, 'GenericName': u'Dress Material', 'SizeAvailable': u'Not Applicable', 'MaxLengthCholi': '', 'ItemTag': u'Enigmatic Off White Salwar Kameez', 'SubCategory': u'Other - Party Wear', 'Description of Blouse/Choli/Bottom': u'Paired With A Matching Bottom', 'Colour': u' Off White', 'Work': u'Lace|Resham', 'ExpressQty': 0, 'Occasion': u'Christmas,Diwali,Eid,Festival,Kitty Party,Mehendi,Navratri,Party Wear,Sangeet,Wedding', 'Weight': 1, 'Description of Dupatta': u'Comes With A Matching Dupatta', 'DeliveryDays': 8}, 28853: {...}}

键是

[28852, 28853, 28854, 28855, 28856, 28857, 28858, 28859, 28860, 28861, 28862, 28863]

当我使用产品[&#39; 28852&#39;]

访问它时
Traceback (most recent call last):

    print products['28852']['ProductNo']
KeyError: '28852'

1 个答案:

答案 0 :(得分:3)

当密钥为整数时,您正在访问str 28852。请访问28852