I have a dictionary that needs to be referred to by other functions. Rather than make it global, I pass the dictionary as an argument.
def functionA(dictionary):
dictionary = {}
functionB(dictionary)
print(f"In A, after B, length: {len(dictionary)}")
def functionB(dictionary):
dictionary["A"] = "some value"
dictionary["B"] = "another value"
def main():
dictionary = {}
functionA(dictionary)
print(f"Back in main. Length: {len(dictionary)}")
if __name__ == "__main__":
""" This is executed when run from the command line """
main()
In the above code, main() initializes dictionary as empty and passes it to functionA(), which also (redundantly) sets it to empty and passes it to functionB(), which adds a couple of entries.
After main() returns from functionA(), I expected dictionary to have the two entries added by functionB(). However, it was empty. The output was:
In A, after B, length: 2
Back in main. Length: 0
If, however, I remove the redundant dictionary = {} in functionA (i.e., the second line of the above code block), the problem goes away and I get the following output:
In A, after B, length: 2
Back in main. Length: 2
I don't see why the dictionary = {} statement in functionA() causes the subsequently added items to not get transferred back to main(). Any insights? I feel like there's something fundamental here that I'm clueless about.