[Solved] Python comparing elements in two lists


Now that you’ve fixed the original problem, and fixed the next problem with doing the check backward, and renamed all of your variables, you have this:

for match in dictionary:
    if any(match in value for value in sentences):
        print match

And your problem with it is:

The way I have the code written i can get the dictionary items but instead i want to print the sentences.

Well, yes, your match is a dictionary item, and that’s what you’re printing, so of course that’s what you get.

If you want to print the sentences that contain the dictionary item, you can’t use any, because the whole point of that function us to just return True if any elements are true. It won’t tell you which ones—in fact, if there are more than one, it’ll stop at the first one.

If you don’t understand functions like any and the generator expressions you’re passing to them, you really shouldn’t be using them as magic invocations. Figure out how to write them as explicit loops, and you will be able to answer these problems for yourself easily. (Note that the any docs directly show you how to write an equivalent loop.)

For example, your existing code is equivalent to:

for match in dictionary:
    for value in sentences:
        if match in value:
            print match
            break

Written that way, it should be obvious how to fix it. First, you want to print the sentence instead of the word, so print value instead of match (and again, it would really help if you used meaningful variable names like sentence and word instead of meaningless names like value and misleading names like match…). Second, you want to print all matching sentences, not just the first one, so don’t break. So:

for match in dictionary:
    for value in sentences:
        if match in value:
            print value

And if you go back to my first answer, you may notice that this is the exact same structure I suggested.

You can simplify or shorten this by using comprehensions and iterator functions, but not until you understand the simple version, and how those comprehensions and iterator functions work.

2

solved Python comparing elements in two lists