[英]How to get all dict keys where values contain given substring
我正在編寫一個程序,該程序制作一個字典,其中的鍵具有長文本句子的值。
該程序的目標是讓我輸入一個數字,Python 抓取網站並從抓取中編譯字典,然后從我的文本中搜索字符串的值。 例如,假設字典如下所示:
myDict = {"Key1": "The dog ran over the bridge",
"Key2": "The cat sleeps under the rock",
"Key3": "The house is dark at night and the dog waits"}
假設我想搜索值並將具有相關字符串的鍵返回給我。 因此,如果我在數字上輸入“dog”,它會在字典中掃描所有具有“dog”的值,然后返回具有相關值的鍵,在本例中為“Key1”和“Key3”。
我在堆棧交換的其他地方嘗試了一些這樣做的方法,例如這里: How to search if dictionary value contains certain string with Python
然而,這些都沒有奏效。 無論字符串如何,它要么只給我第一個 Key,要么返回錯誤消息。
我希望它不區分大小寫,所以我想我需要使用 re.match,但是我在使用這個 dict 的正則表達式並獲得任何有用的回報時遇到了麻煩。
您查看的解決方案是搜索每個字母。 我的解決方案通過查看整個字符串來解決這個問題,它返回一個數組而不是第一個值。
myDict = {"Key1": "The dog ran over the bridge",
"Key2": "The cat sleeps under the rock",
"Key3": "The house is dark at night and the dog waits"}
def search(values, searchFor):
listOfKeys = []
for k in values.items():
if searchFor in k[1]:
listOfKeys.append(k[0])
return listOfKeys
print(search(myDict, "dog"))
它將 output:
['Key1', 'Key3']
這是一個使用列表理解的版本。 https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
d = {
"Key1": "The dog ran over the bridge",
"Key2": "The cat sleeps under the rock",
"Key3": "The house is dark at night and the dog waits",
}
def find(values, key):
key = key.lower()
return [k for k, v in values.items() if key in v.lower()]
print(find(d, "dog"))
如果這將是經常做的事情,那么確保 dic 值都是小寫的開始並以這種方式存儲它們是值得的。
d = {
"Key1": "The dog ran over the bridge",
"Key2": "The cat sleeps under the rock",
"Key3": "The house is dark at night and the dog waits",
}
for k in d:
d[k] = d[k].lower()
def find(values, key):
key = key.lower()
return [k for k, v in values.items() if key in v]
print(find(d, "dog"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.