Skip to content
Advertisement

How to check the dict results if the input is only part of the keyword?

I have a dict and input like that, and now I want to it can search the input even though it is only part of key words, so how to solve it?

input = "a"
dict = {'aaa':111,'bbb':222,'ccc':333}
print(dict[input])

P.S Assuming there is no conflict between input and dict keywords, for example,

input ='a'
dict = {'aaa':111,'abc':222}

is impossible

Advertisement

Answer

If there can be no conflict, or if you’re happy to take the first key that matches the input if there is, you could search the keys to find one which starts with the input string:

input = "a"
dic = {'aaa':111,'bbb':222,'ccc':333}
dic[[k for k in dic.keys() if k.startswith(input)][0]]

Output:

111
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement