0

Set-up

I have the following dictionary,

d={'City':['Paris', 'Berlin','Rome', 'London']}

and the following one-element list,

 address=['Bedford Road, London NW7']   


Problem

I want to check if one of the cities is in the address.


Tried so far

(1)

for x in d['City']:
  if x in address:
    print('yes')
  else: 
    print('no')

only prints no.

(2)

for x in d['City']:
  r = re.compile(x)
  newlist = list(filter(r.match, address)) 

gives a TypeError: 'str' object is not callable. Got this one from this answer which seems to be what should solve this, but the error doesn't help.

How do I go about?

Community
  • 1
  • 1
LucSpan
  • 1,831
  • 6
  • 31
  • 66

3 Answers3

2

Your solution #1 was actually quite close, but it doesn't work, because address is a list of string, not a string itself.

So, it will work perfectly fine, if you just take first element of list address i.e. address[0].

Alternatively, you can try this:

>>> any(i in address[0] for i in d['City'] )
True

For code snippet, you can use:

if any(i in address[0] for i in d['City'] ):
    print 'Yes'
else:
    print 'No'
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
1

Since your address is a one-element list, you should check address[0] instead of address:

for x in d['City']:
    if x in address[0]:
        print('yes')
    else:
        print('no')
Jere Käpyaho
  • 1,305
  • 1
  • 10
  • 29
0

If you aren't increasing the size of the list:

for x in d['City']:
    if x in address[0]:
        print('yes')
    else: 
        print('no')
lordingtar
  • 1,042
  • 2
  • 12
  • 29