【问题标题】:How to get all dict keys where values contain given substring如何获取值包含给定子字符串的所有dict键
【发布时间】:2020-09-24 00:20:33
【问题描述】:

我正在编写一个程序来制作一个字典,其中的键具有长文本句子的值。

该程序的目标是让我输入一个数字,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 并获得任何有用的回报时遇到了麻烦。

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

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

    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']
    

    【讨论】:

    • 小改进:在循环中使用for key, value in values.items(),然后使用keyvalue 而不是k[0]k[1]。使用有意义的名称(而不是 0 和 1)可以使代码更易于理解。
    【解决方案2】:

    这是一个使用列表推导的版本。 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"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 2021-04-19
      • 1970-01-01
      • 2021-09-17
      相关资源
      最近更新 更多