-1

I already see the post Dynamically get dict elements via getattr?, but i can't solve my problem.

I want do something similar, but I'm a bit confused. I want set (not get) the data in the correspondent dictionary, but I get this error

AttributeError: type object 'Dictionary' has no attribute 'VERBS'.

My code is:

class Dictionary:
    def __init__(self):
        self.VERBS = dict()
        self.REFERENCER = dict()

   def setDictionary(self, fileDictionary, name):
        methodCaller = Dictionary()
        dictionary = "self."+name.upper()
        dictionary = getattr(Dictionary, name.upper())
        dictionary = fileDictionary.copy()

Can you see what I'm doing wrong? Because I don't understand completely that.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
benpay
  • 61
  • 1
  • 8
  • I think what you want to do is `dictionary = getattr(methodCaller, name.upper())` but I do not understand what you want to achieve exactly. – ettanany Dec 02 '16 at 12:01
  • You haven't indicated what line causes the error, nor enough code to recreate the error, nor the desire result/output. – martineau Dec 02 '16 at 12:29

1 Answers1

1

I think that this is what you are looking for:

class Dictionary:
    def __init__(self):
        self.VERBS = dict()
        self.REFERENCER = dict()

   def setDictionary(self, fileDictionary, name):
        setattr(self, name.upper(), fileDictionary)

This uses setattr to assign fileDictionary to the member with the name name.upper() on self

The error that the code in the question has results from attempting to access the name on the class where it doesn't exist rather than on the instance where it exists.

It is also possible to write the method as:

def setDictionary(self, fileDictionary, name):
    dictionary = getattr(self, name.upper())
    dictionary.update(fileDictionary)

Which might be closer to what you were attempting.

Note that these two behave differently if the passed dictionary is mutated. The first binds the object to the name on the instance. The second updates the existing dictionary with the items from the passed dictionary.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dan D.
  • 73,243
  • 15
  • 104
  • 123