作者:Gakki
01. 查找相同部分与不同部分
test_1 = {
'a': 22,
'b': 33,
'c': 44
}
test_2 = {
'c': 11,
'b': 33,
'd': 2
}
# 查找相同部分
print("查找相同部分:")
print(test_1.keys() & test_2.keys())
print(test_1.items() & test_2.items())
# 查找不同部分
print("查找不同部分:")
print(test_1.keys() - test_2.keys())
输出结果
查找相同部分:
{'b', 'c'}
{('b', 33)}
查找不同部分:
{'a'}
02. 过滤指定键
test_1 = {
'a': 22,
'b': 33,
'c': 44
}
test_2 = {
'c': 11,
'b': 33,
'd': 2
}
# 排除指定键
test_3 = {key: test_1[key] for key in test_1.keys() - {"a", "d"}}
print(test_3)
输出结果
{'b': 33, 'c': 44}
其他
- dict.keys()、dict.values() 和 dict.items() 返回的都是试图对象(view objects),提供了字典实体的动态视图,这就意味着字典改变,试图也会跟着改变。
注:我们不能对视图对象进行任何修改,因为字典的的视图对象都是只读的;python2.x 是直接返回列表。