python 如何获取所有值包含给定子字符串的dict键

xmq68pz9  于 2023-05-21  发布在  Python
关注(0)|答案(4)|浏览(149)

我正在写一个程序,它可以创建一个字典,字典中的键和值都有很长的文本句子。
这个程序的目标是让我输入一个数字,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并获得任何有用的返回时遇到了麻烦。

z5btuh9x

z5btuh9x1#

你看到的解决方案是搜索每个字母。我的解决方案通过查看整个字符串来解决这个问题,它返回一个数组而不是第一个值。

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"))

它将输出:

['Key1', 'Key3']
inb24sb2

inb24sb22#

这里有一个使用列表解析的版本。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"))
j2cgzkjk

j2cgzkjk3#

我发现使用Array.filter()更容易一些:

const 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"}

const searchString = "dog";
const res = Object.keys(myDict).filter((key) => myDict[key].includes(searchString));

console.log(res);
oxcyiej7

oxcyiej74#

Iterating Through .items()应该会给予结果:

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"}

for key, value in myDict.items():
    if "dog" in value.lower():
        print(key)

相关问题