Python Key Error无法解析字段

时间:2018-05-22 16:44:25

标签: python

我正在编写脚本并迭代列表以将其转换为JSON。我的代码:

Mbody是我从中提取信息的列表的名称。

index = 38
payload = {}

i = 0
while i < Number_SKUs: 
    SKU_size = 2
    size_index = 4
    value_index = 1
    time_index = 4
    ms_index = 2

    payload[i].sku = Mbody[index:(index + SKU_size*2)]
    index = index + SKU_size*2
    print(payload[i].sku)
    i+=1

出于某种原因,这导致了

Traceback (most recent call last):

File "parser.py", line 101, in <module> payload[i].sku = Mbody[index:(index + SKU_size*2)]
KeyError: 0

我搜索了堆栈交换,发现了几个类似的问题,但没有一个回答我的问题。什么是迭代列表并解析skus的最佳方法?这最终将成为JSON,但我暂时可以在数组中使用它,并使用dict将其放入JSON中。

1 个答案:

答案 0 :(得分:2)

在python中,你必须命名字典的键以与它们进行交互。

p['a']['b']
# This is element b of p['a']

p['a'].b
# This is function b in object p['a']

默认情况下,虚线表示法不可用,但有些人solutionsadd that

忽略这些,我们可以对您的代码进行一些更改,以便开始使用通常的表示法。

index = 38
# This can just be a list, because i is continuous between 0 and Number_SKUs
payload = []

i = 0
while i < Number_SKUs:
    SKU_size = 2
    size_index = 4
    value_index = 1
    time_index = 4
    ms_index = 2

    # Each item is going to be a new dictionary, which we will
    # eventually add the the list of payloads
    new_payload = {}

    # Now we can create a dict entry for key 'sku' in new_payload
    new_payload['sku'] = Mbody[index:(index + SKU_size * 2)]

    # We can't do this, because tag_size is undefined
    #
    # index = index + tag_size * 2

    # We can't do this, because we have not yet added a 'tag' key 
    # to payload.
    #
    # print(payload[i]['tag'])

    # Now append new_payload to payload
    payload.append(new_payload)
    i += 1