"Basic Python Tutorial (second edition)" Learning Note Dictionary (4th chapter)
To create a dictionary:
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}
lst=[(' Key1 ', ' value1 '), (' Key2 ', ' value2 ')]; D=dict (LST)
D=dict (key1= ' value1 ', key2= ' value2 ')
Dictionary basic operations:
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; Len (d) ==> 2 #字典中的键值对数量
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; d[' Key1 '] ==> ' value1 ' # key is K value
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; d[' key1 ']= ' newvalue ' ==> ' key1 ': ' NewValue ' # Assignment
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; Del d[' Key2 ' ==> d={' key1 ': ' value1 '} #删除键为k的项
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; ' Key1 ' in D ==> True #检查字典中是否有键k
Formatted string for dictionary:
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; "% (key1)"% d?????
Dictionary method:
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.clear () ==> d={} # Clear All items
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.copy () # Copy
From copy import deepcopy; d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; Deepcopy (d) # deep copy
{}.fromkeys ([' Key1 ', ' Key2 ']) ==> {' Key2 ': None, ' Key1 ': none} #创建字典
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.get (' key1 ') ==> ' value1 ' #获得值
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.has_key (' Key1 ') ==> True #是否有该键
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.items () ==> [(' Key2 ', ' value2 '), (' Key1 ', ' value1 ')] # all items
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.iteritems () # Iterate all items
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.keys () ==> [' Key2 ', ' key1 '] #全部键
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.iterkeys () #迭代全部键
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.pop (' key1 ') ==> ' value1 ', d={' key2 ': ' value2 '} #移除并pop key1
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.popitem () ==> (' Key2 ', ' value2 '), d={' key1 ': ' value1 '} #移除并pop?
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.setdefault (' Key1 ', ' defaultValue1 ') ==> ' value1 ' #类似于get, if not, set default value
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; x={' key2 ': ' UPDATE '}; D.update (x) ==> d={' key2 ': ' Update ', ' key1 ': ' value1 '} #用一个字典更新另一个字典
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.values () ==> [' value2 ', ' value1 '] #全部值
d={' key1 ': ' value1 ', ' key2 ': ' value2 '}; D.itervalues () # Iterate all values
"Basic Python Tutorial (second edition)" Learning Note Dictionary (4th chapter)