python字典key不能是可以是啥類型
python中字典的key不能是可變類型。字典可存儲任意類型對象,其中值可以取任何數(shù)據(jù)類型,但鍵必須是不可變的,如字符串、數(shù)字或元組。語法格式:【d = {key1 : value1, key2 : value2}】。
字典是另一種可變?nèi)萜髂P停铱纱鎯θ我忸愋蛯ο蟆?/p>
字典的每個鍵值(key=>value)對用冒號(:)分割,每個對之間用逗號(,)分割,整個字典包括在花括號({})中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
鍵必須是唯一的,但值則不必。
值可以取任何數(shù)據(jù)類型,但鍵必須是不可變的,如字符串,數(shù)字或元組。
代碼實現(xiàn):
dict = {’Alice’: ’2341’, ’Beth’: ’9102’, ’Cecil’: ’3258’}
內(nèi)容擴展:
Python中字典的key都可以是什么?
答:一個對象能不能作為字典的key,就取決于其有沒有__hash__方法。所以所有python自帶類型中,除了list、dict、set和內(nèi)部至少帶有上述三種類型之一的tuple之外,其余的對象都能當key。
比如數(shù)值/字符串/完全不可變的元祖/函數(shù)(內(nèi)建或自定義)/類(內(nèi)建或自定義)/方法/包等等你能拿出手的,不過有的實際意義不高。還有數(shù)值型要注意,因為兩個不同的相等數(shù)字可以有相同的哈希值,比如1和1.0。
解釋:
代碼版本: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().
字典的鍵可以是任意不可變類型,需要注意的是tuple元組作為鍵時,其中不能以任何方式包含可變對象。
到此這篇關(guān)于python字典key不能是可以是啥類型的文章就介紹到這了,更多相關(guān)python字典key不能是什么類型內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究2. 三個不常見的 HTML5 實用新特性簡介3. Angular獲取ngIf渲染的Dom元素示例4. php面向?qū)ο蟪绦蛟O(shè)計介紹5. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp6. 無線標記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁7. 使用.net core 自帶DI框架實現(xiàn)延遲加載功能8. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析9. php測試程序運行速度和頁面執(zhí)行速度的代碼10. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析
