0

This is my first question on Stackoverflow so forgive me if the format is not totally correct.

PROBLEM:

Is possible to assign attributes for a class based on a dictionary?. I would like to go throw the keys of the dictionary and get from there the name of the attributes. I show down an example.

class Clase():
    def __init__(self, dictionary):
        for key in dictionary.keys():
            self.key = dictionary[key]

dictionary={'attribute1': 'Zara', 'attribute2': 7, 'attribute3': 'First'}
PP = Clase(dictionary)

Big regards and thanks!!

aMg

aMg
  • 1

1 Answers1

0

You could do this:

class Clase():
    def __init__(self, dictionary):
        for key in dictionary.keys():
            setattr(self, key, dictionary[key])

dictionary={'attribute1': 'Zara', 'attribute2': 7, 'attribute3': 'First'}
PP = Clase(dictionary)

print(PP.attribute1)
DomTomCat
  • 6,707
  • 1
  • 39
  • 57