Search code examples
python-3.xclassdictionaryinstance-variableskeyerror

Python3: Edit dictionary class instance variable


class myClass:
    def __init__(self):
        self.myClassDict = {}

    def ADD_DictPair(self, Value, Key):
        #Per ShadowRanger's Solution (Solved)
        #self.myClassDict[Value] = Key #Wrong Code
        self.myClassDict[Key] = Value  #Correct Code

    def get_myDict(self):
        return self.myClassDict


InstanceOfmyClass = myClass()
InstanceOfmyClass.ADD_DictPair("Value1","Key1")
InstanceOfmyClass.ADD_DictPair("Value2","Key3")
InstanceOfmyClass.ADD_DictPair("Value3","Key3")

print(InstanceOfmyClass.get_myDict()["Key1"])

    Desired Output: "Value1"

    Error: print(InstanceOfmyClass.get_myDict()["Key1"])
           KeyError: 'Key1'

Python3 in Windows // Sublime Text 3

My goal is to interact with the dictionary through it's class method to Add, Call, and Edit values.


Solution

  • def ADD_DictPair(self, Value, Key):
        #Per ShadowRanger's Solution (Solved)
        #self.myClassDict[Value] = Key #Wrong Code
        self.myClassDict[Key] = Value  #Correct Code