How do I make Python dictionary members accessible via a dot "."?
For example, instead of writing mydict['val']
, I'd like to write mydict.val
.
Also I'd like to access nested dicts this way. For example
mydict.mydict2.val
would refer to
mydict = { 'mydict2': { 'val': ... } }
I ended up trying BOTH the AttrDict and the Bunch libraries and found them to be way to slow for my uses. After a friend and I looked into it, we found that the main method for writing these libraries results in the library aggressively recursing through a nested object and making copies of the dictionary object throughout. With this in mind, we made two key changes. 1) We made attributes lazy-loaded 2) instead of creating copies of a dictionary object, we create copies of a light-weight proxy object. This is the final implementation. The performance increase of using this code is incredible. When using AttrDict or Bunch, these two libraries alone consumed 1/2 and 1/3 respectively of my request time(what!?). This code reduced that time to almost nothing(somewhere in the range of 0.5ms). This of course depends on your needs, but if you are using this functionality quite a bit in your code, definitely go with something simple like this.
See the original implementation here by https://stackoverflow.com/users/704327/michael-merickel.
The other thing to note, is that this implementation is pretty simple and doesn't implement all of the methods you might need. You'll need to write those as required on the DictProxy or ListProxy objects.
Derive from dict and and implement
__getattr__
and__setattr__
.Or you can use Bunch which is very similar.
I don't think it's possible to monkeypatch built-in dict class.
Fabric has a really nice, minimal implementation. Extending that to allow for nested access, we can use a
defaultdict
, and the result looks something like this:Make use of it as follows:
That elaborates a bit on Kugel's answer of "Derive from dict and and implement
__getattr__
and__setattr__
". Now you know how!Not a direct answer to the OP's question, but inspired by and perhaps useful for some.. I've created an object-based solution using the internal
__dict__
(In no way optimized code)I've always kept this around in a util file. You can use it as a mixin on your own classes too.
You can do it using this class I just made. With this class you can use the
Map
object like another dictionary(including json serialization) or with the dot notation. I hope to help you:Usage examples: