0

I am trying to check for equality to see if a dictionary has been changed before doing an action but it overwrites the variable somewhere and always stays the same.

I have tried moving the point in which dict_to_quit is being created to see if I could get it to stay out of the modifications.

       dict[key] = value  #dictionary was created from file                        
    file.close()

    dict_for_quit = dict     # copy of dict to match against if modified
    while (True):
        if (choice == "1"):
            # adds to dict
            break
        elif (choice == "2"):
            # deletes from dict
            break
        elif(choice == "3"):
            if dict_for_quit == dict:
                print("same")
            else:
                print("not same"

Happy Path: dict is copied to dict_for_quit at the beginning. User runs through some options for dict(adds, deletes). Then when user selects a certain option, program checks dict_for_quit against dict to see if there was modifications.

Errors: Program is modifying dict_to_quit whenever someone makes a change to dict even though it's out of the loop the modifications are being made

  • Possible Duplicate of https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy – traintraveler Sep 18 '19 at 04:04
  • Not technically a duplicate. If it were, I wouldn't have asked since this involves a loop that complicates it more than just using == – Brian Hartling Sep 18 '19 at 04:04
  • But still, with or without the loop, dict2 = dict1 creates a reference to the same dict object instead of a copy, which is why your code is not behaving as expected right ? – traintraveler Sep 18 '19 at 04:06

1 Answers1

1

That is not a copy, try dict_for_quit = dict.copy()

salparadise
  • 5,699
  • 1
  • 26
  • 32
  • I didn't even know that existed. Thanks man! Was it because it was calling the entire line when I referenced dict_to_quit that it was modifying it along with dict? – Brian Hartling Sep 18 '19 at 04:02
  • 1
    It creates a reference to the same dict object, as in if you check id(dict1) and id(dict2) with and without the copy, you'll understand what's happening under the hood. – traintraveler Sep 18 '19 at 04:10