Day30(0214) <<
Previous Next >> Day31(0215)
dict字典(一)
dict型別用來表示字典,包含無順序、無重複且可改變內容的多個鍵:值對(key:value pair),簡單來說就是以鍵做為索引來取得字典裡的值,字典前後以大括號標示,各個鍵:值對以逗號隔開,例如:
>>>{"ID":"40823131","name":"Simon"}
{'ID':'40823131','name':'Simon'}
建立字典
可使用Python內建的dict()函式或{}建立字典,例如:
>>>A = {"one":1,"two":2,"three":3}
>>>B = dict({"one":1,"two":2,"three":3}) #同上
>>>C = dict(one=1,two=2,three=3) #同上
>>>D = {} #空字典
取得/新增/變更/刪除鍵:值對
1.取得:建立字典後可利用鍵取得對映的值,例如:
>>>A = {"one":1,"two":2,"three":3}
>>>x = A["one"]
>>>x
1
2.新增/變更:當key尚未存在於字典時,就新增一個鍵為key、值為value的鍵:值對;相反的,當key已經存在時則改變鍵:值隊的值為value,例如:
>>> B = dict({"one":1,"two":2,"three":3})
>>> B["three"] = 4
>>> B
{'one': 1, 'two': 2, 'three': 4}
>>> B["four"] = 4 #新增鍵:值對
>>> B["three"] = 3 #變更
>>> B
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>>
3.刪除:可利用del敘述刪除鍵為key的鍵:值對,例如:
>>> B = dict({"one":1,"two":2,"three":3,"four":4})
>>> del B["four"]
>>> B
{'one': 1, 'two': 2, 'three': 3}
內建函式
眾多內建函式僅有len()函式適用於字典,用於傳回字典包含幾個鍵:值對,例如:
>>> B = dict({"one":1,"two":2,"three":3,"four":4})
>>>len(B)
4
運算子
字典僅支援in & not in及部分比較運算子(==、!=),例如:
>>> B = dict({"one":1,"two":2,"three":3,"four":4})
>>>"two" in B
True
>>>"five" not in B
True
>>> A = dict({"one":1,"two":2,"three":3,"four":4,"five":5})
>>> A == B
False
>>> A != B
True
Day30(0214) <<
Previous Next >> Day31(0215)