# 每天學點Python之dict
字典用來存儲鍵值對,在Python中同一個字典中的鍵和值都可以有不同的類型。
### 字典的創建
創建一個空的字典有兩種方法:
~~~
d = {}
d = dict()
~~~
而創建一個包含元素的字典方法比較多,下面操作結果相同:
~~~
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
~~~
### 字典的查詢
獲取字典中的值只需通過dict[key]來獲取,如果不存在該鍵,會拋出KeyError錯誤;也可用`dict.get(k[,default])`方法來獲取,這個方法即使鍵不存在也不會拋出錯誤,也可以給一個默認的值,在鍵值對不存在時返回:
~~~
>>> a = dict(one=1, two=2, three=3)
>>> a['one']
1
>>> a['four']
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 'four'
>>> a.get('four')
>>> a.get('four',4)
4
~~~
### 字典的修改
要修改字典中的鍵對應的值,只需要取出來直接對它賦值就行,需要注意的是,如果修改的鍵原來不存在,就變成了向字典中增加了一個鍵值對:
~~~
>>> a = dict(one=1, two=2, three=3)
>>> a['one']=10
>>> a
{'two': 2, 'one': 10, 'three': 3}
>>> a['four']=4
>>> a
{'two': 2, 'four': 4, 'one': 10, 'three': 3}
~~~
而`dict.setdefault(key[,default])`在key存在時,不做修改返回該值,如果不存在則添加鍵值對(key, default),其中default默認為None:
~~~
>>> a = dict(one=1, two=2, three=3)
>>> a.setdefault('one')
1
>>> a
{'two': 2, 'one': 1, 'three': 3}
>>> a.setdefault('four')
>>> a
{'two': 2, 'four': None, 'one': 1, 'three': 3}
~~~
批量增加有`dict.update(p)`方法。
### 字典的刪除
如果要刪除一個鍵值對,直接用del方法,試圖刪除一個不存在的鍵值對會拋出KeyError錯誤:
~~~
>>> a
{'two': 2, 'four': 4, 'one': 10, 'three': 3}
>>> del a['four']
>>> a
{'two': 2, 'one': 10, 'three': 3}
>>> del a['four']
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 'four'
~~~
此外同樣可以調用dict.clear()來清空字典。還有`dict.pop(key[,default])`和`dict.popitem()`,這兩個一個是彈出特定鍵對應的鍵值對,另一個彈出任意的一個鍵值對:
~~~
>>> a
{'two': 2, 'one': 10, 'three': 3}
>>> a.pop("one")
10
>>> a
{'two': 2, 'three': 3}
>>> a.popitem()
('two', 2)
>>> a
{'three': 3}
~~~
### 字典的集合
字典可以分別返回它所有的鍵值對、鍵和值,它們的類型都是字典內置類型,可以通過list()轉化為列表:
~~~
>>> a = dict(one=1, two=2, three=3)
>>> a
{'two': 2, 'one': 1, 'three': 3}
>>> a.items()
dict_items([('two', 2), ('one', 1), ('three', 3)])
>>> a.values()
dict_values([2, 1, 3])
>>> a.keys()
dict_keys(['two', 'one', 'three'])
>>> list(a.keys())
['two', 'one', 'three']
~~~