1

I am somewhat new to coding. I have been self teaching myself for the past year or so. I am trying to build a more solid foundation and am trying to create very simple programs. I created a class and am trying to add 'pets' to a dictionary that can hold multiple 'pets'. I have tried changing up the code so many different ways, but nothing is working. Here is what I have so far.

# Created class
class Animal:

# Class Attribute
classes = 'mammal'
breed = 'breed'

# Initializer/Instance Attribrutes
def __init__ (self, species, name, breed):
    self.species = species
    self.name = name
    self.breed = breed

# To get different/multiple user input
@classmethod
def from_input(cls):
    return cls(
            input('Species: '),
            input('Name: '),
            input('Breed: ')
            )

# Dictionary
pets = {}

# Function to add pet to dictionary
def createpet():
    for _ in range(10):
        pets.update = Animal.from_input()
        if pets.name in pets:
            raise ValueError('duplicate ID')

# Calling the function
createpet()

I have tried to change it to a list and use the 'append' tool and that didn't work. I am sure there is a lot wrong with this code, but I am not even sure what to do anymore. I have looked into the 'collections' module, but couldn't understand it well enough to know if that would help or not. What I am looking for is where I can run the 'createpet()' function and each time add in a new pet with the species, name, and breed. I have looked into the sqlite3 and wonder if that might be a better option. If it would be, where would I go to learn and better understand the module (aka good beginner tutorials). Any help would be appreciated. Thanks!

1 Answer 1

0

(First of all, you have to check for a duplicate before you add it to the dictionary.)
The way you add items to a dictionary x is

x[y] = z

This sets the value with the key y equal to z or, if there is no key with that name, creates a new key y with the value z.
Updated code:
(I defined this as a classmethod because the from_input method is one as well and from what I understand of this, this will keep things working when it comes to inheriting classes, for further information you might want to look at this)

@classmethod
def createpet(cls):
    pet = cls.from_input()
    if pet.name in cls.pets:
        raise ValueError("duplicate ID")
    else:
        cls.pets[pet.name] = pet
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.