Appending new values to pre-existing dictionary keys

The set_more function which is meant to append new values to existing keys is giving me issues and I really can’t find why.

info = {}
class Dog:
    def __init__(self,info):
        info["Name"] = input("Set:nDog's name: ")
        info["Age"] = input("Dog's age: ")
        info["Breed"] = input("Dog's breed: ")
    def get_info(self,info):
        self.info = list(info.values())
        infs = []
        for i in range(len(self.info)):
            infs.append(self.info[i])
        print(infs)
        return infs
    def set_more(self,info):
        info.setdefault("Name", []).append(input("Set:nDog's Name: "))
        info.setdefault("Age", []).append(input("Dog's Age: "))
        info.setdefault("Breed", []).append(input("Dog's Breed: "))  
d = Dog(info)
d.get_info(info)
d.set_more(info)
d.get_info(info)

Answer

There are 2 mistakes.

  1. As schwobaseggl mentioned, you need to initialize the values of your dictionaries as lists, so you can append to them later on. You can do this by using brackets: [input(Dog's age: ")]

  2. Instead of using setdefault, just do info["Field"].append(). Elaborating on setdefault, it only returns the value of the field with the given key. It doesn’t allow you to change the dictionary.

Below is the full corrected code.

info = {}
class Dog:
    def __init__(self,info):
        info["Name"] = [input("Set:nDog's name: ")]
        info["Age"] = [input("Dog's age: ")]
        info["Breed"] = [input("Dog's breed: ")]
    def get_info(self,info):
        self.info = list(info.values())
        infs = []
        for i in range(len(self.info)):
            infs.append(self.info[i])
        print(infs)
        return infs
    def set_more(self,info):
        info["Name"].append(input("Set:nDog's Name: "))
        info["Age"].append(input("Dog's Age: "))
        info["Breed"].append(input("Dog's Breed: "))  
d = Dog(info)
d.get_info(info)
d.set_more(info)
d.get_info(info)

Leave a Reply

Your email address will not be published. Required fields are marked *