0

Here's my code, it's a simple classification program for animals.

horse = {
        "name": "Horse",
        "legs": 4,
        "land": "yes",
        "pet": "yes",
        "stripe": "no"
    }

dolphin = {
        "name": "Dolphin",
        "legs": 0,
        "land": "no",
        "pet": "no",
        "stripe": "no"
    }

userIn = dict()
userIn["legs"] = int(input("How many legs does it have? "))
userIn["land"] = input("Is it a land animal (yes/no)? ")
userIn["pet"] = input("Is it a pet? ")
userIn["stripe"] = input("Does it have stripes? ")

animals = [horse, dolphin]

for animal in animals:
    bak = animal
    bak.pop("name")
    print(bak)
    print(animal)
    if bak == userIn:
        print(animal["name"])

But, at the end where I say bak.pop("name"), it also removes "name" from animal.

How do I make it just remove "name" from bak and not animal?

ecjwthx
  • 9
  • 4
  • 1
    When you do `bak = animal` you don't make a copy. You just give the object that has the name `animal` attached to it the additional name `bak`. – Matthias Oct 08 '22 at 15:11
  • @Matthias Thanks for the quick answer! Is there a way to duplicate an object and then assign it to a variable? – ecjwthx Oct 08 '22 at 15:14
  • Expanding on what Matthias said: `bak` and `animal` are not dictionaries. They are variables. Python is different from some other programming languages in that variables can not hold lists or strings or dictionaries or any other kind of object. A Python variable can only hold a _reference_ to an object, and when you write `bak=animal` you are saying, "make `bak` refer to the same object (same dictionary in this case) that `animal` refers to. Answers below explain how to create a new copy from an existing dictionary. – Solomon Slow Oct 08 '22 at 15:33
  • P.S., A dictionary can't hold lists or strings or other objects either. The entries in a dictionary also are just references to other objects. `animal.copy()` gives you a _shallow_ copy of the `animal` dictionary—a new dictionary that refers to all the same objects (strings and numbers in this case) that the original referred to. `copy.deepcopy(animal)` gives you a "deep" copy—A new dictionary that refers to new "deep" copies of all of the objects from the original dictionary. https://docs.python.org/3/library/copy.html – Solomon Slow Oct 08 '22 at 15:38

2 Answers2

1

Try this;

for animal in animals:
    bak = animal.copy() #edit here
    bak.pop("name")
    print(bak)
    print(animal)
    if bak == userIn:
        print(animal["name"])
Sachin Kohli
  • 1,956
  • 1
  • 1
  • 6
-1

Use deepcopy instead of using bak = animal

import copy

for animal in animals:
    bak = copy.deepcopy(animal)
    print(bak)
    print(animal)
    if bak == userIn:
        print(animal["name"])
Kavindu Ravishka
  • 711
  • 4
  • 11