1,利用defaultdict构建一键多值
from collections import defaultdict
pairs = (('a',1),('b',2))
d = defaultdict(list)
for key, value in pairs:
d[key].append(value)
print(d)
输出:
defaultdict(<class 'list'>, {'a': [1], 'b': [2]})
2,利用OrderedDict控制字典中元素的顺序
注:OrderedDict内部维护了一个双向链表导致大小是普通字典的2倍
3,利用zip()将字典的键值反转后排序,获取最小或最大的item
scores = {
'mathematics': 99,
'English':90,
'geography':97,
'biology':80
}
# dict的浅拷贝,深拷贝用deepcopy(会拷贝复杂类型,list,dict...)
others = scores.copy()
# 方法一,获取最大最小item
scores = sorted(zip(scores.values(), scores.keys()))
print(scores)
print(min(scores))
print(max(scores))
# 方法二
s = min(others, key=lambda k: others[k])
m = max(others, key=lambda k: others[k])
print('min: ', s, ', max:', m)
输出:
[(80, 'biology'), (90, 'English'), (97, 'geography'), (99, 'mathematics')]
(80, 'biology')
(99, 'mathematics')
min: biology , max: mathematics
4,字典的几何操作keys()或items()
stud1 = {
'm': 99,
'e':90,
'g':97,
'b':80
}
stud2 = {
'm': 99,
'l':90,
'g':97,
}
print(stud1.keys() & stud2.keys())
print(stud1.keys() - stud2.keys())
print(stud1.keys() - {'m','n'})
print(stud1.items() - stud2.items())
输出
{'g', 'm'}
{'e', 'b'}
{'g', 'e', 'b'}
{('b', 80), ('e', 90)}
5, 从字典中提取子集
stud = {
'math': 99,
'english':90,
'geography':97,
'biology':80
}
# 字典推导式
scores1 = {key:value for key, value in stud.items() if value > 90}
print(scores1)
输出:
{'math': 99, 'geography': 97}