If you store (value, comment)
pairs, for each pair you can use tuple unpacking in the for
statement (note the parenthesis). Although, this is kind of contradicting your "non-indexing" request:
mydict[key] = (value, comment)
for key, (value, comment) in mydict.items():
print(key, value, comment)
Edit: Following specifications in the comments:
You could subclass a dict
, that has another dict
containing the comments as a member. Every regular dictionary method is left as is, but a specific method is implemented to iterate over the items along with a comment. Comments are added by using the corresponding method add_comment
. If you want to include the comments into the initialzation, while keeping full compatibility with regular dictionary construction more work needs to be put into the __init__
definition.
class MyCommentedDict(dict):
def __init__(self, *args, **kwargs):
super(MyCommentedDict, self).__init__(*args, **kwargs)
self._comments = dict()
def add_comment(self, key, comment):
self._comments.update({key:comment})
def commented_items(self):
""" Returns a generator that yields triplets of (key, value, comment).
For all entries without a provided comment `None` is returned as comment."""
return ((key, value, self._comments.get(key, None))
for key, value in self.items())
a_dict = MyCommentedDict({'color': 'blue', 'fruit': 'apple', 'pet': 'dog'})
a_dict.add_comment('color', 'This a is color')
for key, value in a_dict.items():
print(key, value)
>>>color blue
>>>fruit apple
>>>pet dog
for key, value, comment in a_dict.commented_items():
print(key, value, comment)
>>>color blue This a is color
>>>fruit apple None
>>>pet dog None