gpt4 book ai didi

python - 从字典中的值列表中删除值

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:46 25 4
gpt4 key购买 nike

我在 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']
}

我查看了 SO 和 python 词典文档上的类似页面,但找不到任何内容来解决这个特定问题:

https://docs.python.org/2/library/stdtypes.html#dict

How to remove dictionaries with duplicate values from a nested dictionary

How to remove a key from a python dictionary?

编辑

每个键的 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']}

关于python - 从字典中的值列表中删除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37169298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com