Python Key Error无法解析字段

Python Key Error can't parse fields

我正在编写一个脚本并遍历一个列表,将其转换为JSON。我的代码:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

由于某种原因,这导致

1
2
3
4
Traceback (most recent call last):

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

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


在Python中,必须命名字典的键才能与它们交互。

1
2
3
4
5
p['a']['b']
# This is element b of p['a']

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

默认情况下,点式表示法不可用,尽管有些人有添加点式表示法的解决方案。

忽略这些,我们可以对代码进行一些更改,以开始使用常规的符号。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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