I have a class that is a subclass of the standard dict:
class Result(dict):
""" Dict-like object with special methods """
def content(self):
return self.__getitem__('_content')
def attrs(self):
return self.__getitem__('_attrs')
Sample representation in this object:
{
'_attrs': {'id': 1},
'description': 'testtest',
'calories': 1234,
'_content': 'Sample content',
'name': 'qwerty',
'price': 12390
}
I want my class to skip entries with underlined keys during iteration.
>>> for item in data:
>>> print(item)
'description'
'calories'
'name'
'price'
How can i achieve this?
UPDATE:
In addition to the correct answer, I also redefined the keys () and items () methods to hide the underscore keys, even if these methods are used in an iteration:
def __iter__(self):
for key in self.keys():
yield key
def keys(self):
return [key for key in super().keys() if key not in ['_attrs', '_content']]
def items(self):
return [(key, value) for key, value in super().items() if key not in ['_attrs', '_content']]
source
share