Python JSON search problem
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

This one is really annoying me (amateur programmer here)

So I have this JSON transaction data here: https://0bin.net/paste/4Cl1xdXT#A5XO0dCLgAoI9qt4q4+NEUoYz+jDbVQUDYIkIag3VnO

I am trying to iterative over it to find matches where the "name of transaction is 'in' keywords. Now if I pass full string it works and returns a match

substring = 'AMZNMktplace amazon.co.uk GBR GBR 0819'
for transaction in transactions:
    if transaction['name'] in substring:
        print(f'found a match:  {str(transaction)}')

But when I try partial string match it returns nothing:

substring = 'amazon.co.uk'
for transaction in transactions:
    if transaction['name'] in substring:
        print(f'found a match:  {str(transaction)}')

When I am expecting it to return matches where name contains amazon.co.uk

Can someone provide right code and explanation pls? Tip for good explanation I understand.

Thanks
Sam

1 month ago

Crowdsource coding tasks.

3 Solutions


Try:

if substring in transaction['name']:

Instead of:

if transaction['name'] in substring:

Hello @monkeydust.

You are probably going to laugh after the next few lines, but don't feel bad!

It's completely normal when you are beginning.

Let's go first over your working code:

if transaction['name'] in substring:

On this line, you check whether the string from transaction['name'] is present in your substring.
The reason why your code works is because of the following:

transaction['name'] -> 'AMZNMktplace amazon.co.uk GBR GBR 0819'

substring -> 'AMZNMktplace amazon.co.uk GBR GBR 0819'

If statement checks, is transaction['name'] present in the substring? Yes it is and the code passed.

Now, let's look at the not working code:

You have the same if statement but the substring is different.

transaction['name'] -> 'AMZNMktplace amazon.co.uk GBR GBR 0819'

substring -> 'amazon.co.uk'

If statement checks, is transaction['name'] present in the substring? No!
'AMZNMktplace amazon.co.uk GBR GBR 0819' is not present in 'amazon.co.uk',
but inverse works. 'amazon.co.uk' is present in ''AMZNMktplace amazon.co.uk GBR GBR 0819''

This is how in keyword works in Python strings.

Let the money go to charity!

Best regards,
Vladimir

ohh man - cant believe I didn't see that one after doing more complicated things. Thank you Vladamir and Kostasx. Happy to leave this one to charity if you both are. Thanks again.
monkeydust 1 month ago
Absolutely!
VladimirMikulic 1 month ago
Sure, go ahead!
kostasx 1 month ago
View Timeline