DotMap
Install
pip3 install dotmap
Upgrade
Get updates for current installation
pip3 install --upgrade dotmap
Features
DotMap
is a dot-access dict
subclass that
- has dynamic hierarchy creation (autovivification)
- can be initialized with keys
- easily initializes from
dict
- easily converts to
dict
- is ordered by insertion
The key feature is exactly what you want: dot-access
from dotmap import DotMap
m = DotMap()
m.name = 'Joe'
print('Hello ' + m.name)
However, DotMap
is a dict
and you can treat it like a dict
as needed
print(m['name'])
m.name += ' Smith'
m['name'] += ' Jr'
print(m.name)
It also has fast, automatic hierarchy (which can be deactivated by initializing with DotMap(_dynamic=False)
)
m = DotMap()
m.people.steve.age = 31
And key initialization
m = DotMap(a=1, b=2)
You can initialize it from dict
and convert it to dict
d = {'a':1, 'b':2}
m = DotMap(d)
print(m)
print(m.toDict())
And it has iteration that is ordered by insertion
m = DotMap()
m.people.john.age = 32
m.people.john.job = 'programmer'
m.people.mary.age = 24
m.people.mary.job = 'designer'
m.people.dave.age = 55
m.people.dave.job = 'manager'
for k, v in m.people.items():
print(k, v)
print
It also has automatic counter initialization
m = DotMap()
for i in range(7):
m.counter += 1
print(m.counter)
And automatic addition initializations of any other type
m = DotMap()
m.quote += 'lions'
m.quote += ' and tigers'
m.quote += ' and bears'
m.quote += ', oh my'
print(m.quote)
There is also built-in pprint
as dict
or json
for debugging a large DotMap
m.pprint()
m.pprint(pformat='json')
And many other features involving dots and dictionaries that will be immediately intuitive when used.