Add descriptions for keys in a dictionary

Hi,

I learned that we can create a dictionary with key-value pairs in Python. So I wonder can I add some descriptions for my key-value pairs? such as:

dict[key].description =  "comment for my key-value pair"

Is this feasible and how can I achieve this function? Thank you~

Well the approach above won’t work as written - the expression
dict[key].description gets .description from dict[key], which is
the value stored. And the assignment likewise tries to set a
.description attribute on the value.

Your most direct approach is to make a little class with both a dict
for the dict itself, and another dict for the descriptions (or a
dict-of-dicts if you wanted more things than just the description).

Untested incomplete example:

class DescribedDict:
    def __init__(self):
        self.dict = {}
        self.descriptions = {}

You’d need to fill it out with the mapping methods so that they went
through to the .dict. Then you could just access the .descriptions
internal dict for the descriptions.

You can make the above less burdensome by subclassing dict directly:

class DescribedDict(dict):

which makes it all work directly and you’d just need to add the
.descriptions attribute in __init__. It isn’t generally recommended
to subclass the builtin types because they have some weirdnesses, but in
this case it work just fine.

Cheers,
Cameron Simpson cs@cskk.id.au

Hi,

Thank you for your reply, your answer helps me a lot. It seems this is a workaround:

class DescribedDict(dict):
    def __init__(self, descriptions={}):
        self.descriptions = descriptions

Cheers~

I’m surprised you even need this much code. Does this not work?

class DescribedDict(dict):
    def __init__(self):
        self.descriptions = {}

Cheers,
Cameron Simpson cs@cskk.id.au

Yes, I agree with you. Thank you so much~