Python dict get items pop update

一、get方法

 1   dict = {'k1':1,'k2':2}
 2 
 3   dict.get('k1')
 4 
 5   1
 6 
 7   dict.get('k2')
 8 
 9   2
10 
11   dict.get('k3')
12 
13   None
14 
15   dict.get('k3','wohaoshuai')
16 
17   wohaoshuai
18 
19   (如果k3不存在那么就设置为wohaoshuai)

二、items

1   dict.items()
2 
3   dict_items([('a', 1), ('b', 2)])

三、pop

1   dict.pop('k1')
2 
3   dict
4 
5   {'k2':2}

四、update

1   d2 = {'k3':3}
2 
3   dict.update(d2)
4 
5   dict
6 
7   {'k1':1,'k2':2,'k3':3}

五、有序字典

1 import collections
2 dic = collections.OrderedDict()
3 dic['k1'] = 'v1'
4 dic['k2'] = 'v2'
5 dic['k3'] = 'v3'
六、defaultdict(设置字典默认值)
 1 from collections import defaultdict
 2 values = [11,22,33,44,55,66,77,88,99,90]
 3 my_dict = defaultdict(list)
 4 for value in values:
 5     if value > 66:
 6         my_dict['k1'].append(value)
 7     else:
 8         my_dict['k2'].append(value)
 9 print(my_dict)
10 defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 90]})

 

  

posted @ 2018-06-09 17:30  Presley  阅读(279)  评论(0编辑  收藏  举报