Home > Software design >  Python - add comments to dictionary as a property
Python - add comments to dictionary as a property

Time:01-21

I want to assign comments to the key-value pairs in my dictionary, ideally in a way that I can access them directly. Since I'm new to manipulating classes, I only came this far:

class MyDict(dict):
    def __init__(self, *arg, **kwargs):
        super(MyDict, self).__init__(*arg, **kwargs)

mydict = MyDict()
mydict['first'] = 1
mydict['second'] = 2

Is there a way to add a comment to each of the key-value pairs so I can access them like

for key, value, comment in mydict.iteritems():
    print(key, value, comment)

or

for key, value in mydict.iteritems():
    print(key, value, key.comment)  # or value.comment

Any other way is also fine, as long as the comments are directly accessible (meaning not via indexing of lists or so).

CodePudding user response:

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

  •  Tags:  
  • Related