[英]Matching a string with a dictionary value exactly and retrieving the key - python
I have a dictionary which i fetch from MySql DB, the ID is the key and the value is a string (relative Windows path of files to be exact). 我有一本字典,该字典是从MySql DB获取的,ID是键,值是一个字符串(准确来说是文件的Windows相对路径)。 I have another list which has windows path as elements. 我有另一个列表,其中以Windows路径作为元素。 Now, I need to match the list elements with the dictionary values and if exact match is found, i need to retrieve the key for that element, if not present, i'll update in the DB 现在,我需要将列表元素与字典值进行匹配,如果找到完全匹配的内容,则需要检索该元素的键,如果不存在,我将在数据库中进行更新
My current code: 我当前的代码:
for line in f1:
line = line.strip()
try:
index = next(k for (k,v) in self.db_file_list.iteritems() if line in v)
file_list_csv.append(index)
The problem here is: Suppose value in my dictionary is "abc def", "a/b/c" then if i search values "abc" or "a/b" it would still match and give me key value which is not what i want. 这里的问题是:假设我的字典中的值是“ abc def”,“ a / b / c”,那么如果我搜索值“ abc”或“ a / b”,它仍会匹配并给我键值,而不是我想要。
Please help me out, i am a newbie to Python. 请帮帮我,我是Python的新手。 Many thanks in advance! 提前谢谢了!
~Saurav 〜索拉夫
如果你唯一的问题是,你会匹配字符串匹配的为好,然后更换line in v
与line == v
就足够了(小心使用==
在这种情况下,而不是is
: is
做一个身份比较,而==
只是比较值)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.