1.创建字典
>>> dic = {'k1':'v1','k2':'v2','k3':'v3'} >>> dic = dict(k1='v1',k2='v2')
2.索引
>>> dic['k1'] 'v1' >>> dic['k2'] 'v2' >>> dic = {'k1':'v1','k2':'v2'} >>> print(dic.get('k1')) v1 >>> print(dic.get('k2')) v2 >>> print(dic.get('k3')) None >>> print(dic.get('k3','defaultv')) defaultv
3.新增
>>> dic['k4'] = 'v4' >>> dic {'k3': 'v3', 'k2': 'v2', 'k1': 'v1', 'k4': 'v4'} >>> dic = {'k1':'v1','k2':'v2'} >>> dic.update({'k3':'v3'}) >>> print(dic) {'k2': 'v2', 'k1': 'v1', 'k3': 'v3'}
4.删除
>>> del dic['k4'] >>> dic {'k3': 'v3', 'k2': 'v2', 'k1': 'v1'} >>> dic = {'k1':'v1','k2':'v2'} >>> dic.pop('k1') 'v1' >>> dic {'k2': 'v2'}
5.
>>> dic.keys() ['k3', 'k2', 'k1'] >>> dic.values() ['v3', 'v2', 'v1'] >>> dic.items() [('k3', 'v3'), ('k2', 'v2'), ('k1', 'v1')]
6.循环
>>> for k,v in dic.items(): ... print(k,v) ... ('k3', 'v3') ('k2', 'v2') ('k1', 'v1')
7.长度
>>> len(dic) 3
8.清空字典元素
>>> dic = dict(k1='v1',k2='v2') >>> dic {'k2': 'v2', 'k1': 'v1'} >>> dic.clear() >>> dic {}
9.
10.有序字典
>>> import collections >>> dic1 = collections.OrderedDict() >>> dic1['k1'] = 'v1' >>> dic1['k2'] = 'v2' >>> dic1['k3'] = 'v3' >>> print(dic1) OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')]) >>>
11.删除
>>> dic1 = collections.OrderedDict() >>> dic1['k1'] = 'v1' >>> dic1['k2'] = 'v2' >>> dic1['k3'] = 'v3' >>> dic1 OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')]) >>> dic1.pop('k2') 'v2' >>> dic1 OrderedDict([('k1', 'v1'), ('k3', 'v3')]) >>> dic1 = collections.OrderedDict() >>> dic1['k1'] = 'v1' >>> dic1['k2'] = 'v2' >>> dic1['k3'] = 'v3' >>> dic1.popitem() ('k3', 'v3') >>> dic1.popitem() ('k2', 'v2')
12.move_to_end
>>> dic1 = collections.OrderedDict() >>> dic1['k1'] = 'v1' >>> dic1['k2'] = 'v2' >>> dic1['k3'] = 'v3' >>> dic1.move_to_end('k2') >>> dic1 OrderedDict([('k1', 'v1'), ('k3', 'v3'), ('k2', 'v2')])
13.默认字典
>>> dic1 = collections.defaultdict(list) >>> dic1['k1'].append('a') >>> print(dic1) defaultdict(<class 'list'>, {'k1': ['a']})