Python搜索字典键用于搜索输入 [英] Python search dictionary keys for search input

查看:146
本文介绍了Python搜索字典键用于搜索输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我的问题:



我想搜索一个字典,看看是否有任何键包含用户输入的关键字。例如,用户搜索John。

  elif选项== 3:
count = 0
found = None
search_key = input(你想要搜索什么?).lower()
为key,val在telephone_directory.items()中:#takes电话目录中的每个元素
如果search_key在密钥中:#checks是否包含search_key
如果发现是无:
found = val
count = 1
如果发现不是没有:
print()
print(找不到一个匹配请更具体一些。)
print()
count = 2
break

如果发现是无:
print(对不起,+ str(search_key)+未找到。)
print()
function_options()#redirects如果找到,则

不是无,计数< 2:
print(str(search_key)+在目录中找到。)
print(这里是文件+ str(search_key)+:)
打印(str(search_key)+:++ phone_directory [search_key])
print()
function_options()#redirects back
pre>

所以这是我现在所在的地方。无论搜索可能是什么,即使是整个键,它返回未找到。我做错了什么?

解决方案

你需要做几个选择;允许多个比赛,只找到第一场比赛,或者只允许最多一场比赛。



要找到第一场比赛,请使用 next()

  match = next(val for key,val in telephone_directory.items()if search_key in关键)

如果没有,这将引发 StopIteration 比赛被发现;返回默认值或捕获异常:

 #默认为无
match = next((val为key,val in my_dict.items()if search_key in key),None)

try:
match = next(val for key,val in telephone_directory.items()if search_key in key )
除了StopIteration:
print(Not found)

这些版本只会循环查找字典项,直到发现匹配,然后停止; $ / code code code code code code code code code $ phone_directory.items():
如果search_key在密钥中:
print(找到一个匹配!{}。format(val))
break
else:
print(Nothing found)

请注意 else 块只有当循环的被允许完成时,才被调用,并且没有被 break 语句中断。 p>

要查找所有匹配键,请使用列表理解:

  matches = [val for key,val in phone_directory.items()if search_key in key] 

最后,只允许一个匹配,高效地在同一个迭代器上使用两个 next()调用,如果发现第二个匹配则引发错误

$ b

  def find_one_match(d,search_key):
d = iter(d.items())
尝试:
match = next(val为键,val in d,如果search_key在键中)
除了StopIteration:
raise ValueError('Not found')

if $($)
raise ValueError('多于一个匹配')

返回匹配

适应这个在循环方法中,只有在找到第二个项目时才需要破解:

  found = None 
为key,val在telephone_directory.items()中:
如果search_key在key中:
如果找到则为None:
found = val
其他:
打印(找到多个匹配,请更具体)
break
else:
如果发现是无:
打印(没有找到,请重新搜索)
其他:
打印(匹配发现! {}。format(found))

您的版本无效,因为打印未找到'for 每个密钥不匹配,您只能知道,当您迭代了字典中的所有密钥时,您才能直到最终不匹配。 p>

So here's my question:

I want to search a dictionary to see if any key contains a user-inputted keyword. For example, the user searches for John.

elif option == 3:
        count = 0
        found = None
        search_key = input("What do you want to search for? ").lower()
        for key, val in telephone_directory.items(): #takes each element in telephone directory
            if search_key in key: #checks if it contains search_key
                if found is None:
                    found = val
                    count = 1
                if found is not None:
                    print(" ")
                    print("More than one match found. Please be more specific.")
                    print(" ")
                    count = 2
                    break

            if found is None:
                print("Sorry, " + str(search_key) + " was not found.")
                print(" ")
                function_options() #redirects back

            if found is not None and count < 2:
                print(str(search_key) + " was found in the directory.")
                print("Here is the file on " + str(search_key) + ":")
                print(str(search_key) + ":" + " " + telephone_directory[search_key])
                print(" ")
                function_options() #redirects back  

So this is where I am right now. Whatever the search may be, even if it is the entire key, it returns "was not found". What am I doing wrong?

解决方案

You need to make a few choices; allow multiple matches, find only the first match, or only allow for at most one match.

To find the first match, use next():

match = next(val for key, val in telephone_directory.items() if search_key in key)

This will raise StopIteration if no match was found; return a default instead or catch the exception:

# Default to `None`
match = next((val for key, val in my_dict.items() if search_key in key), None)

try:
    match = next(val for key, val in telephone_directory.items() if search_key in key)
except StopIteration:
    print("Not found")

These versions will only loop over the dictionary items until a match is found, then stop; the full for loop equivalent would be:

for key, val in telephone_directory.items():
    if search_key in key:
        print("Found a match! {}".format(val))
        break
else:
    print("Nothing found")

Note the else block; it is only called when the for loop was allowed to complete, and was not interrupted by a break statement.

To find all matching keys, use can use a list comprehension:

matches = [val for key, val in telephone_directory.items() if search_key in key]

Finally, to allow for only one match, efficiently, use two next() calls on the same iterator, and raise an error if a second match is found:

def find_one_match(d, search_key):
     d = iter(d.items())
     try:
         match = next(val for key, val in d if search_key in key)
     except StopIteration:
         raise ValueError('Not found')    

     if next((val for key, val in d if search_key in key), None) is not None:
         raise ValueError('More than one match')

     return match

Adapting that to the for loop approach again, would require you to break only if a second item is found:

found = None
for key, val in telephone_directory.items():
    if search_key in key:
        if found is None:
            found = val
        else:
            print("Found more than one match, please be more specific")
            break
else:
    if found is None:
        print("Nothing found, please search again")
    else:
        print("Match found! {}".format(found))

Your version doesn't work because you print 'not found' for each and every key that doesn't match. You can only know that you didn't match a key until the very end when you've iterated over all the keys in your dictionary.

这篇关于Python搜索字典键用于搜索输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆