Python 键错误,即使键在字典中?我做错了什么?

Python 键错误,即使键在字典中?我做错了什么?,python,dictionary,keyerror,Python,Dictionary,Keyerror,好的,我得到一个键错误,我把它缩小到这个函数: def find_coexistance(D, query): '''(dict,str)->list Description: outputs locations of words in a test based on query Precondition: D is a dictionary and query is a string ''' quer

好的,我得到一个键错误,我把它缩小到这个函数:

    def find_coexistance(D, query):
        '''(dict,str)->list
        Description: outputs locations of words in a test based on query
        Precondition: D is a dictionary and query is a string
        '''
        query = query.split(" ")

        if (len(query) == 1):
            return D[str(query)]
        else:
            return D.intersection(query)
##############################
# main
##############################
file=open_file()
d=read_file(file)
query=input("Enter one or more words separated by spaces, or 'q' to quit:").strip().lower()
a = find_coexistance(d, query)
print (a)
这是我收到的以下输出:

Traceback (most recent call last):
File "C:\Users\hrith\Documents\ITI work\A5_300069290\a5_part1_300069290.py", 
line 135, in <module>
a = find_coexistance(d, query)
File "C:\Users\hrith\Documents\ITI work\A5_300069290\a5_part1_300069290.py", 
line 122, in find_coexistance
return D[str(query)]
KeyError: "['this']"
如果我检查字典中是否有“this”,我会得到:

>>>'this' in d
True
那么我做错了什么????

当您对字符串使用
split()
时,它总是返回一个列表。所以,
“foo-bar”。拆分(“”
给出
[“foo”,“bar”]
。但是
“foo”.split(“”
给出了一个单元素列表
[“foo”]

代码使用字符串列表作为字典索引,而不是普通字符串

def find_coexistance(D, query):
    query = query.split(" ")

    if (len(query) == 1):
        return D[str(query)]   # <-- HERE
    else:
        return D.intersection(query)
def find_共存(D,查询):
query=query.split(“”)
如果(len(query)==1):

return D[str(query)]#正如其他人所指出的,
query.split(“”)
返回一个列表。在上使用str()将列表转换为单个字符串,并在其中包含括号和引号等字符

>>> q = "hello hi there"
>>> query = q.split()
>>> q
'hello hi there'
>>> query
['hello', 'hi', 'there']
>>> str(query) == "['hello', 'hi', 'there']"
True
不管怎样,你最终想要做的是什么?如果您试图将字符串拆分为单词列表,请查找
D
中存在的任何单词,查看每个单词对应的一组数字,最后返回所有这些集合的交集,这样的操作应该可以:

def find_coexistence(D, query):
    query = query.split(" ")
    sets_to_intersect = [ D[word] for word in query if word in D ]
    return set.intersection(*sets_to_intersect)

请更仔细地查看错误消息。失败的键是
“['this']”
,而不是
'this'
query=query.split(“”)
返回字符串列表,而不是字符串。而且您的dict键不是字符串列表,因此找不到它。标准的习惯用法是
query.split(“”[0]
Ok,我明白了,但是如何访问dictionary中的键。这不是访问字典的语法:d[key]确保您试图使用单个字符串而不是列表访问dict<代码>打印(查询)
在您尝试访问之前,如果您想检查;但是错误消息已经告诉了你很多。编辑:正如@DYZ所说,不要做
str(query)
,这将尝试使用string-representation-of-a-list-of-string!你应该使用
D[query[0]]
,而不是
D[str(query)]
而不是实际的字符串(!),
intersection
调用在代码中也是有问题的,但这可能是故意遗漏的。是的,我留到以后再说。谢谢你的帮助!
>>> q = "hello hi there"
>>> query = q.split()
>>> q
'hello hi there'
>>> query
['hello', 'hi', 'there']
>>> str(query) == "['hello', 'hi', 'there']"
True
def find_coexistence(D, query):
    query = query.split(" ")
    sets_to_intersect = [ D[word] for word in query if word in D ]
    return set.intersection(*sets_to_intersect)