I am creating a custom class for my project which is a recursive list of dictionaries. The attribute my_list
is a list of dictionaries in which case I want to iterate over each of the keys, in each of the dictionaries, within the one object.
The code below is my current attempt. I have seen this solution TypeError: 'type' object is not iterable - Iterating over object instances which gets the same error message but the difference is I want to iterate within a class not over all the objects of a particular class.
class List_of_dicts:
def __init__(self):
self.my_list = []
def add(self, item: dict):
self.my_list.append(item)
l = List_of_dicts()
l.add({'a': 1, 'b': 2})
l.add({'c': 3, 'd': 4})
for obj in l:
print(obj.key)
I get this error:
TypeError: 'List_of_dicts' object is not iterable
I expect the iteration to be over the keys: a, b, c, d, in that order.
How do I implement the iterative behaviour which will allow me to iterate over a class like this?