1.字典的集合操作
old_dict = {
"m1":80,
"m2":90,
"m3":50
}
new_dict = {
"m1": 80,
"m3": 90,
"m4": 50
}
old_set = set(old_dict.keys())
new_set = set(new_dict.keys())
#取交集
update_set = set(old_set.intersection(new_set))
print(update_set)
显示结果:{'m1', 'm3'}
#取差集
delete_set = old_set.symmetric_difference(update_set)
print(delete_set)
显示结果:{'m2'}
add_set = set(new_set.symmetric_difference(update_set))
print(add_set)
显示结果:{'m4'}
2.python计数器
counter:继承于dict,对dict方法的一种加工与处理,用于对象中元素的计数,结果以字典的形式显示出来。
import collections
obj = collections.Counter('ddddjj4499gg;oo')
print(obj)
显示结果:Counter({'d': 4, 'j': 2, '4': 2, '9': 2, 'g': 2, 'o': 2, ';': 1})
for value in obj.elements():
print(value)
显示结果:
d
d
d
d
j
j
4
4
9
9
g
g
for key,value in obj.items():
print(key,value)
显示结果:
d 4
j 2
4 2
9 2
g 2
; 1
o 2
#计数器的更新操作
obj = collections.Counter(['eric','tom','marry'])
print(obj)
显示结果:Counter({'11': 1, '22': 1, '33': 1})
obj.update(['jack','chuizi'])
print(obj)
显示结果:Counter({'22': 2, '33': 2, '11': 1, '44': 1})
#计数器的删除操作
obj.subtract(['33','44','55'])
print(obj)
显示结果:Counter({'22': 2, '11': 1, '33': 1, '44': 0, '55': -1})
3.构造有序字典
#普通方法构造有序字典
dic1 = {'k1':'v1','k2':'v2','k3':'v3'}
li = ['k1','k2','k3']
for i in li:
print(dic1[i])
显示结果:
v1
v2
v3
#使用OrderedDict()方法
dic1 = collections.OrderedDict()
dic1['k1'] = 'v1'
dic1['k2'] = 'v2'
dic1['k3'] = 'v3'
print(dic1)
OrderedDict的move_to_end方法
dic1.move_to_end('k1')
print(dic1)
旧的显示结果:OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
新的显示结果:OrderedDict([('k2', 'v2'), ('k3', 'v3'), ('k1', 'v1')])
OrderedDict的方法
dic1.popitem() #后进先出的原则
print(dic1)新的显示结果:OrderedDict([('k1', 'v1'), ('k2', 'v2')])ret = dic1.pop('k2') #没有原则,可以任意指定key来排除,同时该方法还会将踢出的value返回
print(dic1)新的显示结果:OrderedDict([('k1', 'v1'), ('k3', 'v3')])
print(ret)
显示结果:v2
4.默认字典
dic = collections.defaultdict(list) #字典的默认value为一个空的列表
dic['k1'] = 'ellen'
print(dic)
显示结果:defaultdict(<class 'list'>, {'k1': 'ellen'})
例子:
values = [11,22,33,44,55]
my_dict = collections.defaultdict(list)
for value in values:
if value < 30:
my_dict['k1'].append(value)
else:
my_dict['k2'].append(value)
print(my_dict)
结果:defaultdict(<class 'list'>, {'k1': [11, 22], 'k2': [33, 44, 55]})
5.可命名元组