16

I was wondering if you could add an attribute to a Python dictionary?

class myclass():
    def __init__(): 
     self.mydict = {}  # initialize a regular dict
     self.mydict.newattribute = "A description of what this dictionary will hold"
     >>> AttributeError: 'dict' object has no attribute 'newattribute'
     setattr(self.mydict, "attribute", "A description of what this dictionary will hold"
     >>> AttributeError: 'dict' object has no attribute 'newattribute'

Is there anyway to quickly add my description attribute without having to copy the dict class and overloading the constructor. I thought it would be simple, but I guess I was wrong.

2 Answers 2

37

Just derive from dict:

class MyDict(dict):
    pass

Instances of MyDict behave like a dict, but can have custom attributes:

>>> d = MyDict()
>>> d.my_attr = "whatever"
>>> d.my_attr
'whatever'
Sign up to request clarification or add additional context in comments.

Comments

4

If you feel like creating your own class would be overkill, you can also drop-in replace the dict with a collections.UserDict.

Untested example:

from collections import UserDict

d = UserDict({"foo": "bar"})
d.description = "my dict with attributes"
d["baz"] = 42

For reference:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.