Search code examples
pythonmongodbfor-loopfor-in-loop

Super simple nested Pythonic for-in loops not functioning correctly... something to do with inputs


I have a simple piece of code that is not working and I can't begin to figure out why.

The code is as follows:

def myFunction(otherDictionary, mongoDbCollection):

    for p in otherDictionary:

        print('hi')

        for d in mongoDbCollection:

            print('hello')

Obviously the final goal isn't printing a bunch of hi's and hello's but did this purely for debugging purposes when it seemed like the looping mechanism was not functioning properly.

When I call this function to my dismay, a single hi is printed, then all of the hellos, followed by the rest of the his. Or something like this:

hi
hello
hello
hello
hello
hi
hi
hi
hi

rather than:

hi
hello
hello
hello
hello
hi
hello
hello
hello
hello

and so on.....

It definitely has something to do with the function's inputs as when I changed otherDictionary & mongoDbCollection each to [1,2,3,4,5] to debug this issue it printed the hi's and hello's as expected.

What could possible be in the inputs that would cause such an issue?

mongoDbCollection = a collection from my mongo database

otherDictionary is just a simple dictionary with keywords and respective counts for each like this:

{ 'randomKey': 10, 'otherRandomKey': 3, 'evenMoreRandomKey': 14 }

Could weird characters/symbols in the key's be causing an error like this?

I am completely stumped! The code is too simple for it not to be working...


Solution

  • I don't use mongoDB, so I might be completely off base here but:

    Is it possible mongoDbCollection is a generator? Generators can only be iterated over once. The second time you try to iterate over it, it wouldn't be able to and it would basically be an empty iterable.

    That would cause behavior similar to what you showed in your question: the initial "hi" would be printed once, the mongoDbCollection would be iterated through printing "hello" x amount of times, and then "hi" would be printed for the remainder of the first for loop.

    It would look something like this:

    hi
    hello
    hello
    hello
    # "hello" however many times are in mongoDbCollection ...
    hi
    hi
    hi
    # "hi" however many times are in otherDictionary ...
    

    To fix it, you would have to create an object that could be iterated over an infinite amount of times (e.g. a list or a dict, whatever most closely matches mongoDbCollection).

    def myFunction(otherDictionary, mongoDbCollection):
        collection = list(mongoDbCollection) # or use dict or some other iterable object
        for p in otherDictionary:
            print('hi')
            for d in collection:
                print('hello')