python字典是python中非常重要的一個基礎類型,它是一個高效的基礎類型,不僅在編寫程式的時候經常用到,就連python底層的實現都大量的使用了字典。
主要從幾個方面去學習python的字典
1. 字典的基本使用2. 字典的擴充和針對它的一些類庫(針對特殊用途的字典)3. 自訂自己的字典4. 字典的底層實現
字典的基本使用
建立字典
建立字典有很多種方式,但是要注意一點的是,字典的鍵必需是能夠雜湊的,因此字典的鍵的雜湊值應該在對象的生命週期中是不會變的,這其中包括不可變類型如:str, bytes, int,還有frozen set, 和不包含可變類型項的元組,以及實現了eq()和hash()方法的hash值不變的對象。
下面列舉了一些構造字典的方法
(只考慮方法,並未關注效率問題, 關於效率問題在深入研究之後來分析)
直接構造字典的方式
a = {‘one’ : 1, ‘two’ : 2, ‘three’ : 3}
通過Factory 方法建立字典
傳字典參數的方法構造字典:
b = dict(one=1, two=2, three=3)
使用zip方法構造
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})
列表對元組的方式
f = dict(([‘one’, 1], [‘two’,2],[‘three’,3]))
fromkeys建立預設值字典:
g = dict.fromkeys([‘one’,’tow’,’three’], 1)
字典推導式
h = {value:index+1 for index, value in enumerate(['one','tow','three'])}
可見python中的字典是非常強大的,它的操作非常豐富和方便,下面列舉一些常用的操作 常用操作
字典中有哪些方法,怎麼使用了
首先來看下字典的類圖
dict_test = {1: ‘one’, 2: ‘two’, 3: ‘three’} container
可以使用 in 來判斷元素是否存在:
>>> 1 in dict_test
True mapping
>>> dict_test.keys()dict_keys([1, 2, 3])>>> dict_test.values()dict_values(['one', 'two', 'three'])>>> dict_test.items()dict_items([(1, 'one'), (2, 'two'), (3, 'three')])
注: 在python3中這三個方法返回的都是視圖, 另外可以通過key取得值
>>> dict_test[1]
‘one’ 也可以直接給key配對值
>>> dict_test[4] = 'four'>>> dict_test
{1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’} 以及使用get方法取得值,如果沒有這個key返回預設值
>>> dict_test.get(1, '1')
‘one’
>>> dict_test.get('1', '1')
‘1’ sized
擷取字典的長度
>>> len(dict_test)
3 iterable
可以遍曆和是迭代對象(以鍵進行遍曆)
>>> for value in dict_test:... print(value)...
1
2
3
>>> from collections import Iterable>>> isinstance(dict_test, Iterable)
True
>>> iter(dict_test)
iterator
變成迭代器
>>> iter_test = iter(dict_test)>>> next(iter_test)
1
>>> next(iter_test)
2
>>> next(iter_test)
3
>>> next(iter_test)
Traceback (most recent call last):
File “”, line 1, in
StopIteration 其他一些方法
>>> dir(dict_test)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
常用的方法
pop 移除並返回移除的鍵對應的值, 需要傳一個key參數
>>> dict_test.pop(1)
‘one’
>>> dict_test
{2: ‘two’, 3: ‘three’}
同上, popitem移除並返回移除的索引值對
>>> dict_test.popitem()
(2, ‘two’)
>>> dict_test
{3: ‘three’}
setdefault 方法類似於get方法,只不過在沒有找到鍵的情況下會將這個鍵對應的值設定成預設值,並將這個值返回,如果有這個鍵,直接返回鍵對應的值
>>> dict_test.setdefault(4, 'four')
‘four’
>>> dict_test
{1: ‘one’, 2: ‘two’, 3: ‘three’, 4: ‘four’}
直接刪除字典中的索引值對
>>> del dict_test[1]>>> dict_test
{2: ‘two’, 3: ‘three’, 4: ‘four’}
copy方法, 直接調用copy()為淺拷貝, 即建立了一個新對象,但內容實際上是用的原對象內容的引用, 請看下面的這個例子
>>> dict_test = {'one':1, 'two':[1,1]}>>> dict_copy = dict_test.copy()>>> dict_copy['two'].append(1)>>> dict_test['two']
[1, 1, 1]
使用深拷貝就不會有這個問題
dict_test = {'one':1, 'two':[1,1]}import copydict_deep_copy = copy.deepcopy(dict_test)
dict_deep_copy['two'].append(1)
dict_test['two']
[1, 1]
部分方法前面已經有示範了,這裡不再說明, update用於字典合并,合并有很多種方法,而且經常用到, 合并和更新字典
這裡列舉一些方法:
dict1 = dict([(1,'one'), (2,'two')])dict2 = {2:'two_two',3:'three'}
直接用update方法(這種情況會改變字典)
>>> dict1.update(dict2)>>> dict1
{1: ‘one’, 2: ‘two_two’, 3: ‘three’}
可以使用copy方法或者Factory 方法,新建立一個字典從而不改變原有字典
>>> dict1_copy = dict1.copy() # dict(dict1)>>> dict1_copy.update(dict2)>>> dict1_copy
{1: ‘one’, 2: ‘two_two’, 3: ‘three’}
>>> dict1
{1: ‘one’, 2: ‘two’}
使用解除綁定再組合的方式,這種方式存在一些問題,如下:
>>> dict(dict1, **dict2)
Traceback (most recent call last):
File “”, line 1, in
TypeError: keyword arguments must be strings
因此這種方式只適合key為可作為變數名字的情況
同樣可以使用字典推導式的方式進行字典合并
>>> {key:value for d in [dict1, dict2] for key, value in d.items()}
{1: ‘one’, 2: ‘two_two’, 3: ‘three’}
全部遍曆相加的方法,類似於前面的推導式
>>> dict(list(dict1.items()) + list(dict2.items()))
{1: ‘one’, 2: ‘two_two’, 3: ‘three’}
使用串連操作符 ‘|’
>>> dict(dict1.items() | dict2.items())
{1: ‘one’, 2: ‘two’, 3: ‘three’}
>>> dict(dict2.items()|dict1.items())
{1: ‘one’, 2: ‘two_two’, 3: ‘three’}
這裡覆蓋的順序變了, 如果有重複的key將以第一個字典中key的值作為最終合并的值
藉助於其他類庫
>>> from itertools import chain >>> dict(chain(dict1.items(), dict2.items()))
{1: ‘one’, 2: ‘two_two’, 3: ‘three’}
>>> from collections import ChainMap>>> ChainMap({}, dict2 ,dict1 )
ChainMap({}, {1: ‘one’, 2: ‘two’}, {2: ‘two_two’, 3: ‘three’})
>>> dict(ChainMap({}, dict1, dict2))
{1: ‘one’, 2: ‘two’, 3: ‘three’}
這裡第一個空字典,是為了不改變dict1中的值, 而且注意字典的排放順序, dict1需要放到最後,因為我們需要dict2中的值覆蓋dict1中的值, 這種方式不進行字典遍曆,因為它首先產生了一個view,在尋找的時候才會去匹配,ChainMap並不會直接變成 dict, 需要dictFactory 方法進行轉換, 這種情況適合合并多個字典的情況
dict3 = {3:'three_three', 4:'four'}>>> dict(ChainMap({}, dict3, dict2, dict1))
{1: ‘one’, 2: ‘two_two’, 3: ‘three_three’, 4: ‘four’}
注意字典在參數中的位置, 需要更新的字典放最後
全部解除綁定的方式(這種方便快捷的方式只在python3.5以上有效)
>>> {**dict1, **dict2}
{1: ‘one’, 2: ‘two_two’, 3: ‘three’}
除了合并比較兩個字典的大小也常用 比較字典
由於在python2.1之後有增加了更加豐富的比較符, 但python2又一直保留著cmp這個內建函數,因此可以直接通過cmp方法進行比較但是在python3中這個內建方法已經移除,需要自己去實現那些比較符對應的方法,比如 < 對應著 _lt_, 其他類似: <= _le_, == _eq_, != _ne_, > _gt_, >= _ge_.
字典的比較順序,在python2中遵守下面的規則
首先比較字典的長度, 然後比較字典的鍵,最後比較字典的值
而在python3中需要自己去實現那些比較符方法
dict1 = {1:'one', 3:'three'}dict2 = {2:'two', 3:'three_three'}
condition = True if dict1 >= dict2 else Falsecondition
---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-26-6e55c3e20291> in <module>()----> 1 condition = True if dict1 >= dict2 else False 2 conditionTypeError: unorderable types: dict() >= dict()
dict1.__lt__(dict2)
NotImplemented
另外要說的一點就是, 字典中的鍵是無序的集合,因此可以利用集合的一些操作來處理字典, 比如找到第一個字典中沒有的索引值對,可以利用集合的差補來做
{key: dict1[key] for key in set(dict1) - set(dict2)}
{1: ‘one’}
還有其他一些字典的操作,比如給字典排序, 擴充和改造自己的字典類型等,下次有時間總結下。
上面這些例子是在python3.4.3下面測試的