iT邦幫忙

0

Python 索引錯誤:list indices must be integers or slices, not dict

  • 分享至 

  • xImage
  •  

目前有一份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
   ...

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

1
obarisk
iT邦研究生 2 級 ‧ 2023-04-08 17:51:45

不對。用 list 存 dict 本身就是問題。

1
一級屠豬士
iT邦大師 1 級 ‧ 2023-04-08 22:31:11
listData = [{'ProductNo': 'P00001'}, 
            {'ProductNo': 'P00002'}, 
            {'ProductNo': 'P00003'}, 
            {'ProductNo': 'P00004'}, 
            {'ProductNo': 'P00005'}]

for elem in listData:
    print(f'元素:{elem}, 元素型態:{type(elem)}')

print()

for idx, elem in enumerate(listData):
    print(f'{idx} -> {elem}')

print()
for elem in listData:
    print(elem['ProductNo'])
元素:{'ProductNo': 'P00001'}, 元素型態:<class 'dict'>
元素:{'ProductNo': 'P00002'}, 元素型態:<class 'dict'>
元素:{'ProductNo': 'P00003'}, 元素型態:<class 'dict'>
元素:{'ProductNo': 'P00004'}, 元素型態:<class 'dict'>
元素:{'ProductNo': 'P00005'}, 元素型態:<class 'dict'>

0 -> {'ProductNo': 'P00001'}
1 -> {'ProductNo': 'P00002'}
2 -> {'ProductNo': 'P00003'}
3 -> {'ProductNo': 'P00004'}
4 -> {'ProductNo': 'P00005'}

P00001
P00002
P00003
P00004
P00005

你觀察一下上面的執行結果.

至於你的寫法,確定真的沒問題嗎? 你是用幾版的Python?

allyhsuu iT邦新手 5 級 ‧ 2023-04-08 23:33:46 檢舉

不好意思,沒檢查到錯誤,已修正,感謝。
另外,我用的是3.7.4的版本!

我要留言

立即登入留言