字典訪問操作【每日一個知識點(diǎn)第185期-Python】
把相應(yīng)的鍵放入到方括號中,如下實(shí)例:
#!/usr/bin/Python3 dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} print ("dict['Name']: ", dict['Name']) print ("dict['Age']: ", dict['Age'])
以上實(shí)例輸出結(jié)果:
dict['Name']: Runoob dict['Age']: 7
如果用字典里沒有的鍵訪問數(shù)據(jù),會輸出錯誤如下:
#!/usr/bin/Python3 dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}; print ("dict['Alice']: ", dict['Alice'])
以上實(shí)例輸出結(jié)果:
Traceback (most recent call last): File "test.py", line 5, in <module> print ("dict['Alice']: ", dict['Alice']) KeyError: 'Alice'
《Python入門每日一個知識點(diǎn)》欄目是馬哥教育Python年薪20萬+的學(xué)員社群特別發(fā)起,分享Python工具、Python語法、Python項(xiàng)目等知識點(diǎn),幫助大家快速的了解Python學(xué)習(xí),快速步入Python高薪的快車道。
http://www.vfuj.cn/73198.html