[英]python check if word matches portion of key in a dictionary
Could someone help with this?有人可以帮忙吗? I would like to do a partial search for a word in dictionary keys.
我想对字典键中的单词进行部分搜索。
$ cat dic.py
dic={"pluto_123":"yes"}
print("pluto" in dic)
$python dic.py
False
You can see the result is False which is expected but instead, I need to get the result as True taking pluto_123 contains pluto您可以看到结果是 False ,这是预期的,但相反,我需要得到结果为 True 以pluto_123包含pluto
Thanks in Advance提前致谢
With your check, you need to have a key exactly called pluto
.通过您的检查,您需要有一个完全称为
pluto
的密钥。 Since you don't have one, you got False
.因为你没有,所以你得到了
False
。
You need to check if your substring is present in a key, for every key in your dictionary:对于字典中的每个键,您需要检查您的 substring 是否存在于键中:
>>> print(any("pluto" in key for key in dic))
True
You can do it, but then you waste the capability of the dictionary to do a lookup in O(1).你可以这样做,但是你浪费了字典在 O(1) 中进行查找的能力。
for key in dic:
if "pluto" in key:
print("found")
break
Here's another solution that utilizes an extension of the dict
class.这是另一个利用
dict
class 扩展的解决方案。
class MyDict(dict):
def __contains__(self, item):
for key in self.keys():
if item in key:
return True
return False
d = MyDict()
d.update({"pluto_123":"yes"})
print("pluto" in d)
Output: Output:
True
Keep in mind this will have a readability & performance impact.请记住,这将对可读性和性能产生影响。
You can also create a new type of dict this way.您也可以通过这种方式创建新类型的 dict。
class NewDict(dict):
def __contains__(self, key):
return any(key in k for k in self.keys())
dic=NewDict(pluto_123 ="yes", plu45="90")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.