python 遍历list元素是dict的错误:list indices must be integers or slices, not dict
程序员文章站
2022-05-29 21:07:19
...
list_data = [{"sku_id":"800001183","launch_time":"2021-05-29 00:00:00"},
{"sku_id":"800001182","launch_time":"2021-05-29 00:00:00"},
{"sku_id":"800001172","launch_time":"2021-05-29 00:00:00"},
{"sku_id":"800001171","launch_time":"2021-05-29 00:00:00"},
{"sku_id":"800001181","launch_time":"2021-05-24 00:00:00"},
{"sku_id":"800001180","launch_time":"2021-05-24 00:00:00"},
{"sku_id":"800001170","launch_time":"2021-05-24 00:00:00"},
{"sku_id":"800001183","launch_time":"2021-05-29 00:00:00"}]
在python里遍历list的方法是:
for i in list_data:
print(list_data[i])
但是针对元素是dict的列表这么写会报错:
list indices must be integers or slices, not dict
因为这个时候i并不是数字0,1,2......而是第一个dict,第二个dict
所以要这么遍历:
for i in list_data:
print(i['sku_id'])
print(i['launch_time'])