Bee*_*Gee 1 python dictionary python-2.7
我在Windows 7中使用Python 2.7.
我有一个字典,并希望从另一个字典中删除与(键,值)对相对应的值.
例如,我有一本字典t_dict.我想删除字典中的相应(键,值)对,values_to_remove以便我最终得到字典final_dict
t_dict = {
'a': ['zoo', 'foo', 'bar'],
'c': ['zoo', 'foo', 'yum'],
'b': ['tee', 'dol', 'bar']
}
values_to_remove = {
'a': ['zoo'],
'b': ['dol', 'bar']
}
# remove values here
print final_dict
{
'a': ['foo', 'bar'],
'c': ['zoo', 'foo', 'yum'],
'b': ['tee']
}
Run Code Online (Sandbox Code Playgroud)
我已经查看了关于SO和python词典文档的类似页面,但找不到任何解决这个特定问题的东西:
https://docs.python.org/2/library/stdtypes.html#dict
编辑
t_dict每个键中不能有重复的值.例如,永远不会有
t_dict['a'] = ['zoo','zoo','foo','bar']
试试这个,
for k, v in t_dict.items():
for item in values_to_remove.get(k, ()):
v.remove(item)
# Output
{'a': ['foo', 'bar'], 'c': ['zoo', 'foo', 'yum'], 'b': ['tee']}
Run Code Online (Sandbox Code Playgroud)