Let's say I have a list of dictionaries like:
list_of_dicts = [
{'id': 'something', type: 'type_a', blah...},
{'id': 'anotherthing', type: 'type_b', blah...},
{'id': 'yetanotherthing', type: 'type_c', blah...},
etc.
]
And I have some objects like:
class Base(object):
def __init__(self, blah):
self.blah = blah
class TypeA(Base):
class TypeB(Base):
class TypeC(Base):
etc.
I want to iterate over the list and then depending on a condition, let's say:
for elem in list_of_dicts:
if elem['type'] == 'type_a':
my_obj = TypeA(blah)
elif elem['type'] == 'type_b':
my_obj = TypeB(blah)
etc.
I might have many classes. How do I avoid this really long if/elif of choosing the right object? Is there a dynamic way to achieve this? Better yet, am I trying to be too clever by not explicitly choosing and setting for every type of object?
Each object may have 10+ attributes to set and this if/elif block is incredibly long and getting difficult to read/maintain.
UPDATE:
The more than likely answer is that I am going about this totally wrong. My original goal is that I have this nested dictionary and I want to "clean it up"/enhance each dictionary element a particular way. Maybe for an element with 'type'=='type_a', I want to add a couple of new keys. If 'type'=='type_b', maybe I want to edit the name of a key or two. If 'type'=='type_c', I want to edit the value of a certain key, etc. There could be 30,40 maybe 50 different types. So I start with a "messy" nested dict and get back a "clean" one, modified my way.
My original approach was to have a class for each type. And then each class could have their own @property
decorated methods to set certain attributes a particular way. And they all inherit from the same base class which would have a method that returns a dictionary with all the attributes as keys.