Tania
Tania

Reputation: 1925

Dictionary pattern matching error

I have this dictionary:

mydict = {'greet': ['Hello123','hi45'],
          'say': 'thankyou789',
          'slang': ['Bmyguest','Bmyfriend']}

I want to fetch the keys based on partially matched user inputs, e.g.:

If the user enters 'Brightback', I should return 'slang' since only 'slang' contains entries starting with 'B'. If the user enters 'Hello' or 'hi', I should return 'greet'.

input="Brightback"
for key, value in mydict.iteritems():
    if input.startswith(value):
        print key

this gives out the error:

TypeError: startswith first arg must be str, unicode, or tuple, not list

Upvotes: 0

Views: 74

Answers (2)

namit
namit

Reputation: 6957

You have to implement one more check; if value is a list or not; if list then if any value starts with that value or not..

In [1]: mydict={'greet':['Hello123','hi45'],'say':'thankyou789','slang':['Bmyguest','Bmyfriend']}

In [2]: myinput="Brightback"

In [3]: for key, value in mydict.iteritems():
   ...:     if isinstance(value, list):
   ...:         if any(x.startswith(myinput) for x in value):
   ...:             print key
   ...:     elif value.startswith(myinput):
   ...:         print key
   ...:         

In [4]: myinput="hi"

In [5]: for key, value in mydict.iteritems():
   ...:     if isinstance(value, list):
   ...:         if any(x.startswith(myinput) for x in value):
   ...:             print key
   ...:     elif value.startswith(myinput):
   ...:         print key
   ...:         
greet

In [6]: myinput="thank"

In [7]: for key, value in mydict.iteritems():
   ...:     if isinstance(value, list):
   ...:         if any(x.startswith(myinput) for x in value):
   ...:             print key
   ...:     elif value.startswith(myinput):
   ...:         print key
   ...:         
say

In [8]: 

Upvotes: 1

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

If value is a list you need to iterate over it.

Below I put the value in a list if it's a string, otherwise I leave it as it is.

I've changed the name to values as it is more than one:

input="Brightback"
for key, values in mydict.iteritems():
    values = [values] if type(values) is str else values
    for value in values:
        if input.startswith(value):
            print key
            break

Also, to save printing the same key twice, I break out of the value in values loop to try the next key.

I like to simplify code, and your loop is really a search for any value matching the start of the word. Python has a builtin function any:

input="Brightback"
for key, values in mydict.iteritems():
    values = [values] if type(values) is str else values
    if any(input.startswith(value) for value in values):
        print key

Upvotes: 1

Related Questions