Python — dict 類
- 2020 年 1 月 13 日
- 筆記
Python dict類常用方法:
class dict(object):
def clear(self): #清除字典中所有元素形成空字典,del是刪除整個字典;
>>> test
{'k2': 'v2', 'k1': 'v1'}
>>> test.clear()
>>> test
{}
def copy(self): # 淺拷貝只拷貝第一層,其他層指向原數據,如果原數據改變其他
都會跟著改變,而深拷貝
不變;
>>> cp =
{'c1': 'cv1', 'c2': {'d2': {'e1': 'ev1'}, 'd1': 'dv1'}}
>>> c1 = cp.copy()
>>> c2 = cp
>>> import copy
>>> c3 = copy.deepcopy(cp) # 深拷貝,拷貝完整數據
>>> cp['c2']['d2']['e1'] = 'cp_copy'
>>> cp
{'c1': 'cv1', 'c2': {'d2': {'e1': 'cp_copy'}, 'd1': 'dv1'}}
>>> c1
{'c1': 'cv1', 'c2': {'d2': {'e1': 'cp_copy'}, 'd1': 'dv1'}}
>>> c2
{'c1': 'cv1', 'c2': {'d2': {'e1': 'cp_copy'}, 'd1': 'dv1'}}
>>> c3
{'c1': 'cv1', 'c2': {'d2': {'e1': 'ev1'}, 'd1': 'dv1'}}
def fromkeys(*args, **kwargs): # 將所有key都賦予相同的值,第一參數為key,第二個
參數為value如果沒有第二個參數則默認為none;
>>> test
{'k2': 'v2', 'k1': 'v1'}
>>> ret = test.fromkeys([1,2,3],'t')
>>> ret
{1: 't', 2: 't', 3: 't'}
def get(self, k, d=None): # get方法如果找不到元素則返回none 不會返回錯誤,
或者指定返回資訊;
>>> test = {'k1':'v1','k2':'v2'}
>>> test.get('k1')
'v1'
>>> print(test.get('k3'))
None
>>> print(test.get('k3','ok'))
ok
def items(self): # 讀取字典中所有值形成列表,主要用於for循環;
>>> test
{'k2': 'v2', 'k1': 'v1'}
>>> test.items()
dict_items([('k2', 'v2'), ('k1', 'v1')])
def keys(self): # 讀取字典中所有key值形成列表,主要用於in 的判斷;
>>> test
{'k2': 'v2', 'k1': 'v1'}
>>> test.keys()
dict_keys(['k2', 'k1'])
def pop(self, k, d=None): # 指定刪除某一元素,注必須指定key;
>>> test
{'k2': 'v2', 'k1': 'v1'}
>>> test.pop('k1')
'v1'
>>> test
{'k2': 'v2'}
def popitem(self): # 相比pop它是無序刪除某一元素,無需指定key;
>>> test
{'k2': 'v2', 'k4': 'v4', 'k3': 'v3', 'k1': 'v1'}
>>> test.popitem()
('k2', 'v2')
>>> test.popitem()
('k4', 'v4')
>>> test.popitem()
('k3', 'v3')
def setdefault(self, k, d=None): # 如果有值則返回值,如果沒值則默認添加none,
也可以添加指定值;
>>> test
{'k2': 'v2', 'k4': 'v4', 'k3': 'v3', 'k1': 'v1'}
>>> test.setdefault('k1')
'v1'
>>> test.setdefault('k5')
>>> test
{'k2': 'v2', 'k4': 'v4', 'k3': 'v3', 'k5': None, 'k1': 'v1'}
>>> test.setdefault('k6',['k6'])
['k6']
>>> test
{'k2': 'v2', 'k4': 'v4', 'k5': None, 'k1': 'v1', 'k6': ['k6'], 'k3': 'v3'}
def update(self, E=None, **F): # 更新時,就會循環需要更新的字典每一個元素,
如果原字典中沒有相同元素則添加該元素則在原字典中添加
該元素,如果有相同key則更新value值;
>>> test = {'k1':'v1','k2':'v2'}
>>> uptest = {'u1':1,'u2':2,'k3':3}
>>> test.update(uptest)
>>> test
{'k2': 'v2', 'u1': 1, 'k3': 3, 'u2': 2, 'k1': 'v1'}
def values(self): # 讀取字典中所有values 值並形成列表;
>>> test
{'k2': 'v2', 'k1': 'v1'}
>>> test.values()
dict_values(['v2', 'v1'])