字典有什么特性?【每日一個(gè)知識(shí)點(diǎn)第191期-Python】
字典值可以是任何的 Python 對(duì)象,既可以是標(biāo)準(zhǔn)的對(duì)象,也可以是用戶定義的,但鍵不行。
兩個(gè)重要的點(diǎn)需要記?。?/p>
1)不允許同一個(gè)鍵出現(xiàn)兩次。創(chuàng)建時(shí)如果同一個(gè)鍵被賦值兩次,后一個(gè)值會(huì)被記住,如下實(shí)例:
#!/usr/bin/Python3 dict = {'Name': 'Runoob', 'Age': 7, 'Name': '小菜鳥'} print ("dict['Name']: ", dict['Name'])
以上實(shí)例輸出結(jié)果:
dict['Name']: 小菜鳥
2)鍵必須不可變,所以可以用數(shù)字,字符串或元組充當(dāng),而用列表就不行,如下實(shí)例:
#!/usr/bin/Python3 dict = {['Name']: 'Runoob', 'Age': 7} print ("dict['Name']: ", dict['Name'])
以上實(shí)例輸出結(jié)果:
Traceback (most recent call last): File "test.py", line 3, in <module> dict = {['Name']: 'Runoob', 'Age': 7} TypeError: unhashable type: 'list'
《Python入門每日一個(gè)知識(shí)點(diǎn)》欄目是馬哥教育Python年薪20萬+的學(xué)員社群特別發(fā)起,分享Python工具、Python語法、Python項(xiàng)目等知識(shí)點(diǎn),幫助大家快速的了解Python學(xué)習(xí),快速步入Python高薪的快車道。
http://www.vfte.cn/73198.html