Python报错:TypeError: list indices must be integers or slices, not str

问题概述

首先报错信息的字面意思为,类型错误:列表索引必须是整数或切片,而不是str
代码如下

# 人体行为信息
person_info = items['person_info']
# 行为信息属性
attributes = person_info['attributes']

print(person_info)
print(attributes)

person_info如下

[{'attributes': {'both_hands_leaving_wheel': {'score': 0.12176866084337, 'threshold': 0.75}, 'eyes_closed': {'score': 0.47068807482719, 'threshold': 0.55}, 'no_face_mask': {'score': 0.99440461397171, 'threshold': 0.75}, 'not_buckling_up': {'score': 0.40850603580475, 'threshold': 0.44}, 'smoke': {'score': 0.0083957426249981, 'threshold': 0.48}, 'cellphone': {'score': 0.2926022708416, 'threshold': 0.69}, 'not_facing_front': {'score': 0.6774777173996, 'threshold': 0.5}, 'yawning': {'score': 0.0052815575618297, 'threshold': 0.5}, 'head_lowered': {'score': 0.18483714014292, 'threshold': 0.55}}, 'location': {'score': 0.97045028209686, 'top': 37, 'left': 64, 'width': 244, 'height': 207}}]

报错信息如下
Python报错:TypeError: list indices must be integers or slices, not str_第1张图片

分析原因

列表中嵌套了字典,然后字典中也嵌套了字典,为了区分要取列表中的哪个字典,取值的时候要加字典数据的位置索引也就是下标,比如0,1,2之类
,然后加key值,就可以取出想要的数据值了

解决办法

# 人体行为信息
person_info = items['person_info']
# 行为信息属性
attributes = person_info[0]['attributes']

print(person_info)
print(attributes)

成功取出attributes如下

{'both_hands_leaving_wheel': {'score': 0.12176866084337, 'threshold': 0.75}, 'eyes_closed': {'score': 0.47068807482719, 'threshold': 0.55}, 'no_face_mask': {'score': 0.99440461397171, 'threshold': 0.75}, 'not_buckling_up': {'score': 0.40850603580475, 'threshold': 0.44}, 'smoke': {'score': 0.0083957426249981, 'threshold': 0.48}, 'cellphone': {'score': 0.2926022708416, 'threshold': 0.69}, 'not_facing_front': {'score': 0.6774777173996, 'threshold': 0.5}, 'yawning': {'score': 0.0052815575618297, 'threshold': 0.5}, 'head_lowered': {'score': 0.18483714014292, 'threshold': 0.55}}

你可能感兴趣的:(Python学习,python)