字典在python中的地位想必不用作者多說了,下面直接進入正題。
Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] on win32
>>> dir(dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__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', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys',
'pop', 'popitem', 'setdefault', 'update', 'values','viewitems', 'viewkeys', 'viewvalues']
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
>>>dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__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']
在python2.7.8中查看dict屬性是我們可以看到有一大堆的熟悉的和不熟悉的屬性,下面我們針對每個屬性進行分析和舉例:
普通方法 | python2.7.8 | python3.7.2 | |
---|---|---|---|
clear() | yes | yes | 移除所有元素 |
copy() | yes | yes | 淺複製 點擊示例 |
fromkeys(it[,init]) | yes | yes | 創建一個新字典,將迭代器it裏面的元素設置爲映射裏面的鍵,若有init參數則將其設置爲值。點擊示例 |
get(k[,default]) | yes | yes | 獲取鍵k對應的值,若沒有返回None或default 點擊示例 |
pop(k[,default]) | yes | yes | 返回鍵k對應的值,並移除該鍵值對,若無鍵k則返回None或default,類似於pop()方法 |
popitem() | yes | yes | 隨機返回一個鍵值對,並從字典中移除它 |
setdefault(k, default) | yes | yes | 若字典裏有鍵k,則返回鍵k對應的值,若字典裏面沒有鍵k,則令dict(k)=default,並返回default值。 點擊示例 |
update(m, [*kargs]) | yes | yes | m可以是映射或者鍵值對迭代器,用來更新字典中對應的條目 |
items() | yes | yes | 返回字典的所有鍵值對 點擊示例 |
keys() | yes | yes | 返回所有的鍵,類似於item()方法,python2.7和python3.7返回值不一樣 |
values() | yes | yes | 返回字典中所有的值 |
iterkeys() | yes | no | 返回字典中鍵的迭代器 |
itervalues() | yes | no | 返回字典中值的迭代器 |
viewitems | yes | no | 返回類似集合的對象,顯示字典中的元素,等同於python3.7中的items() |
viewkeys | yes | no | 返回類似集合的對象,顯示字典中的鍵,等同於python3.7中的keys() |
viewvalues | yes | no | 返回類似集合的對象,顯示字典中的值,等同於python3.7中的values() |
特殊方法 | python2.7.8 | python3.7.2 | |
---|---|---|---|
__class__ | yes | yes | 顯示類型,等同於type(dict1) 點擊跳轉 |
__cmp__ | yes | no | cmp函數的字典方法實現 |
__contains__ | yes | yes | 用來判斷字典中是否存在某個鍵,in 語法會調用 |
__getattribute__ | yes | yes | 獲取屬性的方法實現x.__getattribute__(‘name’) <==> x.name |
__delattr__ | yes | yes | x.__delattr__(‘name’) <==> del x.name |
__getitem__ | yes | yes | 取元素x.__getitem__(y) <==> x[y] |
__delitem__ | yes | yes | x.__delitem__(y) <==> del x[y] |
__doc__ | yes | yes | 字典初始化方法實現,dict(mapping),dict(iterable),dict(**kwargs) |
__format__ | yes | yes | format()格式化方法實現 |
__hash__ | yes | yes | 字典的hash表實現 |
__init__ | yes | yes | 初始化實例對象 |
__new__ | yes | yes | 創建實例對象 |
__init_subclass__ | yes | no | 被繼承時使用 |
__iter__ | yes | yes | iter()實現,返回鍵的迭代器 |
__len__ | yes | yes | len()實現,獲取字典的大小 |
__reduce__ | yes | yes | 序列化相關 |
__reduce_ex__ | yes | no | 序列化相關 |
__repr__ | yes | yes | repr()函數實現,字符串輸出方法 |
__setattr__ | yes | yes | x.__setattr__(‘name’, value) <==> x.name = value,設置屬性值 |
__setitem__ | yes | yes | x.__setitem__(i, y) <==> x[i]=y,設置元素值 |
__sizeof__ | yes | yes | 獲取字典大小,指字節數 |
__str__ | yes | yes | 字符串格式化輸出 |
__subclasshook__ | yes | yes | |
__eq__ | yes | yes | x.__eq__(y) <==> x==y |
__ge__ | yes | yes | x.__ge__(y) <==> x>=y |
__gt__ | yes | yes | x.__gt__(y) <==> x>y |
__le__ | yes | yes | x.__le__(y) <==> x<=y |
__lt__ | yes | yes | x.__lt__(y) <==> x<y |
__ne__ | yes | yes | x.__ne__(y) <==> x!=y |
dict.copy()方法示例
# 淺複製,只複製父對象,不復制對象內部的子對象
>>> dict1 = dict(a='ok', b=['yes', 'no'])
>>> dict2 = dict1.copy()
>>> dict1, dict2
({'a': 'ok', 'b': ['yes', 'no']}, {'a': 'ok', 'b': ['yes', 'no']})
>>> dict1['b'].append('oh')#dict1和dict2的中的'b'元素引用了相同的可變數據類型, 因此操作是同步的
>>> dict1['a'] = 'good' #'b'元素引用了不可變數據類型(元組例外,情況更爲複雜),操作不同步
>>> dict1, dict2
({'a': 'good', 'b': ['yes', 'no', 'oh']}, {'a': 'ok', 'b': ['yes', 'no', 'oh']})
dict.fromkey()方法示例
>>> list1 = ['a', 'b', 'c']
>>> dict1 = dict().fromkeys(list1, 'vv')
>>> dict1 #使用該方法創造的字典是新字典
{'a': 1, 'c': 1, 'b': 1}
dict.get()方法示例
>>> dict1 = dict(a='ok', b='oh')
>>> value1 = dict1.get('a')
>>> value2 = dict2.get('c') #若字典中無此鍵,則返回默認值None
>>> value3 = dict3.get('c', 'NoExist') #若字典中無此鍵,則返回指定值
>>> value1, value2, value3
('ok', None, 'NoExist')
dict.setdefault()方法示例
>>> dict1 = dict(a='ok', b='good')
>>> dict2 = dict(dict1)
>>> dict1.setdefault('a', 'bad') #若該鍵存在就返回該鍵對應的值
'ok'
>>> dict2.setdefault('c', 'bad') #若該鍵不存在就將指定值賦值給該鍵,並返回指定值。若無指定值則默認爲None
'bad'
dict1, dict2
({'a': 'ok', 'b': 'good'}, {'a': 'ok', 'c': 'bad', 'b': 'good'})
dict.items()方法示例
python2.7
>>> dict1 = dict(a='ok', b='good')
>>> dict1.items() #python2.7直接返回列表
[('a', 'ok'), ('b', 'good')]
python3.7
>>> dict2 = dict(a='ok', b='good')
>>> dict2.items() #python3.7返回一個dict_items類型實例
dict_items([('a', 'ok'), ('b', 'good')])