Python 索引错误:list indices must be integers or slices, not dic

目前有一份list

listData = [{'ProductNo': 'P00001'},             {'ProductNo': 'P00002'},             {'ProductNo': 'P00003'},             {'ProductNo': 'P00004'},             {'ProductNo': 'P00005'}]

想要分别取出P00001、P00002、P00003...
通常我会这样取值

一笔print(listData[0]['ProductNo']) // P00001多笔for i in listData:    print(listData[i]['ProductNo'])// list indices must be integers or slices, not dict

但发现会报list indices must be integers or slices, not dict的错误
那其实就是我们在进行list的索引的时候也就是我们程式码中的i,是dictionary的关係
print print看就知道了!

for i in listData:    print(i)    // {'ProductNo': 'P00001'}   {'ProductNo': 'P00002'}   {'ProductNo': 'P00003'}   {'ProductNo': 'P00004'}   {'ProductNo': 'P00005'}

所以正确使用迴圈的方式取出dict中的值是这样

for i in listData:    print(i['ProductNo'])    // P00001   P00002   P00003   ...

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章