我正在搜索句点“.”在字典中并尝试删除键/值对,如果我找到它
if "." in dict.values():
#delete key, value pair from the dictionary
我确信这很简单,但我似乎无法找到解释。 感谢您的帮助。
最佳答案
使用字典理解创建一个没有那些不需要的值的新字典。以下是如何操作的示例:
>>> old_dict = {'one': '.', 'two': 2, 'three':3, 'four':'.'}
>>> new_dict = {k:v for k,v in old_dict.iteritems() if not v == '.'}
>>> new_dict
{'three': 3, 'two': 2}
使用 iteritems
而不是 items
可以避免创建中间列表并提高性能。
关于python - 通过匹配值python删除键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19361878/