How to stop dict.pop("foo") from deleting every dict item with name the "foo"?

Question:

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?

Asked By: ecjwthx

||

Answers:

Try this;

for animal in animals:
    bak = animal.copy() #edit here
    bak.pop("name")
    print(bak)
    print(animal)
    if bak == userIn:
        print(animal["name"])
Answered By: Sachin Kohli

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"])
Answered By: Kavindu Ravishka
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.