1、字典python
一、字典的初始化bash
字典是一種key-value結構,和set同樣是無序的
ide
In [160]: d = {} In [161]: type(d) Out[161]: dict In [166]: d = {'a':1, 'b':2} In [167]: d Out[167]: {'a': 1, 'b': 2} In [180]: d = dict({"a":0, "b":1}) In [181]: d Out[181]: {'a': 0, 'b': 1} In [164]: d = dict([["a", 1], ["b", 2]]) # 可迭代對象的元素必須是一個二元組 In [165]: d Out[165]: {'a': 1, 'b': 2} In [168]: d = dict.fromkeys(range(5)) # 傳入的可迭代元素爲key,值爲None In [169]: d Out[169]: {0: None, 1: None, 2: None, 3: None, 4: None} In [170]: d = dict.fromkeys(range(5), "abc") # 傳入的可迭代元素爲key,值爲abc In [171]: d Out[171]: {0: 'abc', 1: 'abc', 2: 'abc', 3: 'abc', 4: 'abc'}
2、字典的基本操做函數
一、增和改
ui
In [173]: d = {'a':1, 'b':2} # 直接使用key作爲索引,對某個不存在的索引賦值會增長KV對 In [174]: d["c"] = 1 In [175]: d Out[175]: {'a': 1, 'b': 2, 'c': 1} In [175]: d Out[175]: {'a': 1, 'b': 2, 'c': 1} In [176]: d["b"] = 1 In [177]: d Out[177]: {'a': 1, 'b': 1, 'c': 1} ## dict.update() 一般用於合併dict In [178]: d.update((("d", 4),("e", 5))) In [179]: d Out[179]: {'a': 1, 'b': 1, 'c': 1, 'd': 4, 'e': 5} In [1]: d = {'a':1, 'b':2} In [2]: d.update({'c':3, 'd':4}) In [3]: d Out[3]: {'a': 1, 'b': 2, 'c': 3, 'd': 4} In [6]: d.update({'c':3, 'd':44}) # 當鍵存在時,其值會更新 In [7]: d Out[7]: {'a': 1, 'b': 2, 'c': 3, 'd': 44}
二、刪spa
## dict.pop() In [23]: help(d.pop) Help on built-in function pop: pop(...) method of builtins.dict instance D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised (END) In [24]: d Out[24]: {'a': 11, 'b': 2} In [25]: d.pop('a') Out[25]: 11 In [26]: d.pop('c') --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-26-adf338c8a0db> in <module>() ----> 1 d.pop('c') KeyError: 'c' In [27]: d.pop('c', 555) Out[27]: 555 In [28]: d.pop('b', 555) Out[28]: 2 In [30]: d Out[30]: {} ## dict.popitem 隨機返回一個KV對的二元組 In [33]: help(d.popitem) Help on built-in function popitem: popitem(...) method of builtins.dict instance D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. In [35]: d = {'a':1, 'b':2} In [36]: d Out[36]: {'a': 1, 'b': 2} In [37]: d.popitem() Out[37]: ('b', 2) In [38]: d Out[38]: {'a': 1} In [39]: d.popitem() Out[39]: ('a', 1) In [40]: d Out[40]: {} In [41]: d.popitem() --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-41-5d3e77a54ba7> in <module>() ----> 1 d.popitem() KeyError: 'popitem(): dictionary is empty' ## dict.clear() In [52]: d = {'a':1} In [53]: d.clear() In [54]: d Out[54]: {} In [55]: d.clear() ## del In [61]: d = {'a':1} In [62]: del d['a'] In [63]: d Out[63]: {} In [64]: del d In [65]: d --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-65-e29311f6f1bf> in <module>() ----> 1 d NameError: name 'd' is not defined
能修改dict的key嗎?對象
只能經過先刪除一個key再增長一個key來變相修改
索引
二、查
ip
1)單個元素的訪問
內存
In [1]: d = {'a':1, 'b':2} In [2]: d Out[2]: {'a': 1, 'b': 2} In [3]: d['a'] Out[3]: 1 In [4]: d['c'] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-4-3e4d85f12902> in <module>() ----> 1 d['c'] KeyError: 'c' ## dict.get() In [5]: help(d.get) Help on built-in function get: get(...) method of builtins.dict instance D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. (END) In [6]: d Out[6]: {'a': 1, 'b': 2} In [7]: d.get('a') Out[7]: 1 In [8]: d.get('c') In [9]: d Out[9]: {'a': 1, 'b': 2} In [12]: d.get('c', 123) Out[12]: 123 In [13]: d Out[13]: {'a': 1, 'b': 2} ## dict.setdefault() 獲取K的值,K不存在時則新增該K和其V,V默認爲None In [14]: help(d.setdefault) Help on built-in function setdefault: setdefault(...) method of builtins.dict instance D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D (END) In [15]: d Out[15]: {'a': 1, 'b': 2} In [16]: d.setdefault('a') Out[16]: 1 In [17]: d.setdefault('c') In [18]: d Out[18]: {'a': 1, 'b': 2, 'c': None} In [19]: d.setdefault('d', 123) Out[19]: 123 In [20]: d Out[20]: {'a': 1, 'b': 2, 'c': None, 'd': 123} In [21]: d.setdefault('a', 123) Out[21]: 1 In [22]: d Out[22]: {'a': 1, 'b': 2, 'c': None, 'd': 123}
1)元素的遍歷
dict的元素是成對出現的
In [23]: d Out[23]: {'a': 1, 'b': 2, 'c': None, 'd': 123} In [24]: for i in d: ...: print(i) ...: a b c d In [25]:
直接用for in 遍歷dict、遍歷的是key
dict.keys()
In [25]: help(d.keys) Help on built-in function keys: keys(...) method of builtins.dict instance D.keys() -> a set-like object providing a view on D's keys (END) In [26]: d Out[26]: {'a': 1, 'b': 2, 'c': None, 'd': 123} In [27]: d.keys() Out[27]: dict_keys(['a', 'b', 'c', 'd'])
dict.values():
In [29]: d Out[29]: {'a': 1, 'b': 2, 'c': None, 'd': 123} In [30]: d.values() Out[30]: dict_values([1, 2, None, 123]) In [35]: lst = list(d.values()) In [36]: lst Out[36]: [1, 2, None, 123]
dict.items()
In [37]: d Out[37]: {'a': 1, 'b': 2, 'c': None, 'd': 123} In [38]: d.items() Out[38]: dict_items([('a', 1), ('b', 2), ('c', None), ('d', 123)]) In [39]: lst = d.items() In [40]: type(lst) Out[40]: dict_items In [41]: lst = list(d.items()) In [42]: lst Out[42]: [('a', 1), ('b', 2), ('c', None), ('d', 123)] In [43]: for k, v in d.items(): ...: print(k, v) ...: a 1 b 2 c None d 123 In [44]:
dict.keys()、dict.value()、dict.items()返回的都相似生成器;它並不會複製一分內存
python2中隊友的方法返回的list,會複製一分內存
字典對Key和Value的限制:
字典的key須要不重複、可hash
字典是無序的
3、標準庫中dict的變體
一、defaultdict 默認字典
In [3]: from collections import defaultdict In [4]: d1 = {} In [5]: d2 = defaultdict() In [6]: type(d1) Out[6]: dict In [7]: type(d2) Out[7]: collections.defaultdict In [8]: d1 Out[8]: {} In [9]: d2 Out[9]: defaultdict(None, {}) In [46]: d2['a'] = 11 In [47]: d2 Out[47]: defaultdict(None, {'a': 11}) In [12]: help(defaultdict) Help on class defaultdict in module collections: class defaultdict(builtins.dict) | defaultdict(default_factory[, ...]) --> dict with default factory | | The default factory is called without arguments to produce | a new value when a key is not present, in __getitem__ only. | A defaultdict compares equal to a dict with the same items. | All remaining arguments are treated the same as if they were | passed to the dict constructor, including keyword arguments. | | Method resolution order: | defaultdict | builtins.dict | builtins.object In [13]: d2 = defaultdict(list) In [14]: d2 Out[14]: defaultdict(list, {}) In [15]: d1['a'] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-15-a9ea8faf9ae0> in <module>() ----> 1 d1['a'] KeyError: 'a' In [16]: d2['a'] Out[16]: [] In [19]: d2 Out[19]: defaultdict(list, {'a': []}) In [20]: d2['a'] Out[20]: [] In [21]: d2 Out[21]: defaultdict(list, {'a': []}) In [22]: d2['a'] = 11 In [23]: d2 Out[23]: defaultdict(list, {'a': 11}) In [24]: d2['a'] Out[24]: 11
default初始化的時候,須要傳入一個函數,這個函數也交工廠函數,當咱們使用下標訪問key的時候,若是這個key不存在,defaultdict會自動調用初始化時傳入的函數,生成一個對象做爲這個key的value。
二、有序字典
In [58]: from collections import OrderedDict In [59]: d = OrderedDict() In [60]: d Out[60]: OrderedDict() In [61]: d['a'] = 1 In [62]: d['b'] = 2 In [63]: d['c'] = 3 In [64]: d Out[64]: OrderedDict([('a', 1), ('b', 2), ('c', 3)]) In [65]: for k, v in d.items(): ...: print(k, v) ...: a 1 b 2 c 3
有序dict會保持插入順序