python字典key不能是可以是啥類(lèi)型
python中字典的key不能是可變類(lèi)型。字典可存儲(chǔ)任意類(lèi)型對(duì)象,其中值可以取任何數(shù)據(jù)類(lèi)型,但鍵必須是不可變的,如字符串、數(shù)字或元組。語(yǔ)法格式:【d = {key1 : value1, key2 : value2}】。
字典是另一種可變?nèi)萜髂P停铱纱鎯?chǔ)任意類(lèi)型對(duì)象。
字典的每個(gè)鍵值(key=>value)對(duì)用冒號(hào)(:)分割,每個(gè)對(duì)之間用逗號(hào)(,)分割,整個(gè)字典包括在花括號(hào)({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
鍵必須是唯一的,但值則不必。
值可以取任何數(shù)據(jù)類(lèi)型,但鍵必須是不可變的,如字符串,數(shù)字或元組。
代碼實(shí)現(xiàn):
dict = {’Alice’: ’2341’, ’Beth’: ’9102’, ’Cecil’: ’3258’}
內(nèi)容擴(kuò)展:
Python中字典的key都可以是什么?
答:一個(gè)對(duì)象能不能作為字典的key,就取決于其有沒(méi)有__hash__方法。所以所有python自帶類(lèi)型中,除了list、dict、set和內(nèi)部至少帶有上述三種類(lèi)型之一的tuple之外,其余的對(duì)象都能當(dāng)key。
比如數(shù)值/字符串/完全不可變的元祖/函數(shù)(內(nèi)建或自定義)/類(lèi)(內(nèi)建或自定義)/方法/包等等你能拿出手的,不過(guò)有的實(shí)際意義不高。還有數(shù)值型要注意,因?yàn)閮蓚€(gè)不同的相等數(shù)字可以有相同的哈希值,比如1和1.0。
解釋?zhuān)?/p>
代碼版本:3.6.3;文檔版本:3.6.6
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append()and extend().
字典的鍵可以是任意不可變類(lèi)型,需要注意的是tuple元組作為鍵時(shí),其中不能以任何方式包含可變對(duì)象。
到此這篇關(guān)于python字典key不能是可以是啥類(lèi)型的文章就介紹到這了,更多相關(guān)python字典key不能是什么類(lèi)型內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 改變 Python 中線程執(zhí)行順序的方法2. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以內(nèi))3. 詳解Python模塊化編程與裝飾器4. Python下使用Trackbar實(shí)現(xiàn)繪圖板5. html小技巧之td,div標(biāo)簽里內(nèi)容不換行6. Python通過(guò)format函數(shù)格式化顯示值7. python web框架的總結(jié)8. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式9. python使用ctypes庫(kù)調(diào)用DLL動(dòng)態(tài)鏈接庫(kù)10. Python性能測(cè)試工具Locust安裝及使用
