在字典键中查找字符串,其中字符串不是dict中的键

时间:2014-02-05 19:59:38

标签: python dictionary key

我在搜索字典列表时试图找到密钥。但是字符串与字典键不完全匹配。这就是我到目前为止所做的:

if string in d.keys():
    print 'found'

我想找到的钥匙。

4 个答案:

答案 0 :(得分:5)

我认为没有什么比通过d键进行线性扫描更好的了。

print [k for k in d if string in k]

答案 1 :(得分:1)

如果这是你的程序依赖的东西,你可以这样做:

   class ApproxDict(dict):

      def __contains__(self, item):
          # item contains the key. Do what you need with it.
          return True # or False again this depends on what you want

使用建议实施__contains__()方法的其他任何解决方案。 这样你就可以自定义查找并保持python的可读性。

对于您在评论中准备好的关键子字符串查找:

    >>> class ApproxDict(dict):
    ...     def __contains__(self, item):
    ...         for key in self.keys():
    ...             if item in key:
    ...                 return True
    ...         return False
    ... 
    >>> d = ApproxDict()
    >>> d['abc123'] = "some value"
    >>> 'bc1' in d
    True
    >>> 'bc2' in d
    False
    >>> 

参见the python data model documentation. 希望有所帮助。

顺便说一下,有一个词典:

    if key in d:
        # whatever

相当于:

    if key in d.keys():
        # whatever

答案 2 :(得分:0)

假设distance比较两个字符串,如果字符串是一个很好的匹配则返回一个较小的数字,而当字符串是一个不匹配时,返回一个更高的数字。 (你必须决定在那里雇用什么,Levenshtein等)。

bestMatch = None
value = None
for k, v in d.items ():
    match = distance (k, searchedKey)
    if bestMatch == None or bestMatch > match:
         bestMatch = match
         value = v
print (value) # the value of the best matched key

答案 3 :(得分:0)

如果我正确理解你的问题,你想要用键模糊字符串匹配。这是我的建议:

>>> keys = ["apple", "plum", "pear", "carrot"]
>>> d = {key:val for key, val in zip(keys,range(4))}
>>> d
{'plum': 1, 'carrot': 3, 'pear': 2, 'apple': 0}
>>>
>>> searchKey = "aple"
>>>
>>> import difflib
>>>
>>> try:
...     searchVal = d[searchKey]
... except:
...     closeKey = difflib.get_close_matches(searchKey, d.keys(), 1)[0]
...     searchVal = d[closeKey]
...
>>> searchVal
0