字符串索引必须是整数,而不是str

时间:2018-08-08 20:54:15

标签: python python-2.7 dictionary

我有以下字典

event = {'records': {'recordId': 1, 'data': 'logHere'}, {'recordId': 2, 'data': 'logHere2'}}

我想使用此循环打印recordId

for record in event['records']:
    print(record['recordId'])

我在String indeces must be integers not str上遇到了print(record['recordId'])错误

我知道为什么会出现此错误,但是我想知道如何重新格式化字典,以便循环将打印recordId。我不想更改循环,我想更改字典。

2 个答案:

答案 0 :(得分:3)

将内部字典包装在列表中:

event = {'records': [{'recordId': 1, 'data': 'logHere'}]}

答案 1 :(得分:0)

event = {'records': [{'recordId': 1, 'data': 'logHere'},
                     {'recordId': 2, 'data': 'logHere2'}]}

您的记录应为项目列表:

>>> for record in event['records']:
        print(record['recordId'])
    1
    2
>>>