Install dotmap
via pip
pip install dotmap
It does everything you want it to do and subclasses dict
, so it operates like a normal dictionary:
from dotmap import DotMapm = DotMap()m.hello = 'world'm.hellom.hello += '!'# m.hello and m['hello'] now both return 'world!'m.val = 5m.val2 = 'Sam'
On top of that, you can convert it to and from dict
objects:
d = m.toDict()m = DotMap(d) # automatic conversion in constructor
This means that if something you want to access is already in dict
form, you can turn it into a DotMap
for easy access:
import jsonjsonDict = json.loads(text)data = DotMap(jsonDict)print data.location.city
Finally, it automatically creates new child DotMap
instances so you can do things like this:
m = DotMap()m.people.steve.age = 31
Comparison to Bunch
Full disclosure: I am the creator of the DotMap. I created it because Bunch
was missing these features
- remembering the order items are added and iterating in that order
- automatic child
DotMap
creation, which saves time and makes for cleaner code when you have a lot of hierarchy - constructing from a
dict
and recursively converting all childdict
instances toDotMap