Reputation:
I am working on a program and stuck on one part. My program accepts a user input of a string which also contains the '*' symbol. What I need to do is match this string with any of the resembling dictionary keys.
For Example:
dict = {'Mazda': [[2, 'brown', '2006']], 'Jaguar': [[1, 'black', '2020']],
'Lamborghini': [[0, 'red', '2009']], 'Camaro SS': [[1, ''Matte Black', '1969']],
'Dodge': [[1, 'grey', '2012']], "twin turbo'camaro": [[2, 'lime green', '2016']] }
If the user enters:
'*amaro'
or
'Cam*ro'
or
'Camar*'
It will find all instances where there is 'Camaro' in the keys of the dictionary.
code so far...
name = input('Enter * for the missing letter ')
name = name.replace('*', '') # I was thinking if I took the hash out I can sort through they keys and find the most similar instances
if name in dict.keys():
nName = dict.get(name)
If the code worked the only output I need is proof of the two keys being found from the users input:
Camaro SS
twin turbo'camaro
Upvotes: 0
Views: 58
Reputation: 26039
Slightly modifying @mrzo's answer, you want to use re.search
with case insensitive search (re.search
instead of re.match
because we are not looking for a complete key match):
name = input('Enter * for the missing letter ')
regex_name = name.replace('*', '.')
for car in cars:
if re.search(regex_name, car, re.IGNORECASE):
print(name, "matches", car)
where cars
is your dictionary. Do not name as dict
.
Using wildcard .
is equivalent to any character in regex.
Upvotes: 1
Reputation: 2135
You can use regular expressions. .
stands for a wildcard sign here
import re
cars = {
'Mazda': [[2, 'brown', '2006']],
'Jaguar': [[1, 'black', '2020']],
'Lamborghini': [[0, 'red', '2009']],
'Camaro SS': [[1, 'Matte Black', '1969']],
'Dodge': [[1, 'grey', '2012']],
"twin turbo'camaro": [[2, 'lime green', '2016']]
}
name = input('Enter * for the missing letter ')
regex_name = name.replace('*', '.')
for car in cars:
if re.match(regex_name, car):
print(name, "matches", car)
Upvotes: 0