0

I have below an object:

class A:
    a:str
    b:str
    c:str

And the dictionary is as below:

d = {"a":"abc","b":"def","d":"itf"}

After populating the dictionary in the object, params a and b should be "abc" and "def" and d should be discarded and c should be None.

How can I achieve this?

Edit: i want to set instance attributes not class attributes in class A.

MarifQ
  • 13
  • 11
  • Are a, b and c instance or class variables? – matszwecja Oct 11 '22 at 12:38
  • You may find the answer here: https://stackoverflow.com/a/1305663/5165980 – Aymen Oct 11 '22 at 12:38
  • not instances but variables of class. – MarifQ Oct 11 '22 at 12:39
  • @Aymen in this answer, all keys will become params of object A. but i dont want key(d) of dictionary to part of object params. – MarifQ Oct 11 '22 at 12:43
  • `for x in A.__annotations__: setattr(A, x, d.get(x, None))`. – ekhumoro Oct 11 '22 at 12:53
  • @ekhumoro can you please explain ? how can i use this ? – MarifQ Oct 11 '22 at 13:43
  • @MarifQ What do you mean? Just run that line of code as it is - there's nothing more to it (assuming `A` and `d` are defined as in your question, and you want to set *class* attributes, as opposed to *instance* attributes). – ekhumoro Oct 11 '22 at 13:59
  • @ekhumoro maybe i didn't clear that in my question, my bad. but i want to set instance attributes not class attributes. – MarifQ Oct 11 '22 at 14:02
  • @MarifQ In that case, you can just replace `A` with the relevant instance variable to achieve exactly the same thing (which could be `self`, if you want to do this in `__init__` or a method of the class). – ekhumoro Oct 11 '22 at 14:03

2 Answers2

1

You can use a classmethod to load each value from the dictionary into the specific class variable.

class A:
    a:str
    b:str
    c:str

    @classmethod
    def loadDict(cls, d:dict):
        cls.a = d.get("a", None)
        cls.b = d.get("b", None)
        cls.c = d.get("c", None)


d = {"a":"abc","b":"def","d":"itf"}

A.loadDict(d)
print(A.a) # "abc"
print(A.c) # None

Trying to get A.d results in an AttributeError.

matszwecja
  • 6,357
  • 2
  • 10
  • 17
0

You can make a dict with the correct variables and update the class's __dict__

class A:
    def __init__(self, **kwargs):
        dictionary = {}
        for k, v in kwargs.items():
            if k in ["a", "b", "c"]:
                dictionary[k] = v

        self.a = None
        self.b = None
        self.c = None

        dictionary["c"] = None

        self.__dict__.update(**dictionary)


# define the dict with the variables and make the object
d = {"a": "abc", "b": "def", "d": "itf"}
objectWithDictVariables = A(**d)

# print the values from the object
print(objectWithDictVariables.__dict__["a"])
print(objectWithDictVariables.__dict__["b"])
print(objectWithDictVariables.__dict__["c"])
Raed Ali
  • 549
  • 1
  • 6
  • 22