首页 > 解决方案 > Pandas:如何在 python 字典中搜索和删除键值对以匹配模式

问题描述

我有一本下面列出的字典。

["key1" : "//This is an entry to be deleted", "key2" : "Good key", "key3", "Good key"]

对于所有以“//”开头的值都是坏键,因此必须删除它们。

如果有人没有得到我的问题,请告诉我。

标签: pythonpandas

解决方案


通过过滤使用字典理解startswith

d = {"key1" : "//This is an entry to be deleted", "key2" : "Good key", "key3": "Good key"}

d = {k:v for k, v in d.items() if not v.startswith('//')}
print (d)
{'key2': 'Good key', 'key3': 'Good key'}

通过过滤使用字典理解startswith

d = {"//key1" : "This is an entry to be deleted", "key2" : "Good key", "key3": "Good key"}

d = {k: v for k, v in dc.items() if not k.startswith('//')}
print (d)
{'key2': 'Good key', 'key3': 'Good key'}

推荐阅读