Access Lists and Dicts with Dotted Path Notation in Python with dotted

dotted

obj = DottedDict({'hello': {'world': {'wide': 'web'}}})

All of these are true:

obj['hello'] == {'world': {'wide': 'web'}}
obj['hello.world'] == {'wide': 'web'}
obj['hello.world.wide'] == 'web'

obj.hello == {'world': {'wide': 'web'}}
obj.hello.world == {'wide': 'web'}
obj.hello.world.wide == 'web'

Example #3: Both working together

obj = DottedCollection.factory({
    'hello': [{'world': {'wide': ['web', 'web', 'web']}}]
})

You can access:

obj['hello'][0]['world']['wide'][0]
obj.hello[0].world.wide[0]
obj.hello[0].world['wide'][0]
obj.hello[0].world['wide.0']
obj.hello['0.world'].wide[0]
...
obj['hello.0.world.wide.0']

 

Example #4: When new values are dicts or lists

obj = DottedCollection.factory(some_obj)

obj['some.path'] = {'hello': 'world'}  # will be converted to a DottedDict
obj['another.path'] = ['hello']  # will be converted to a DottedList

 

Example #5: Shortcuts

from dotted.utils import dot, dot_json

obj = dot({'hello': 'world'})
obj = dot_json('{"hello": "world"}')

 

Example #6: Keys with dots inside!

Well, you can actually use escaped keys, but it's better to avoid them:

from dotted.utils import dot, dot_json
obj = dot({"hello\.world": "Hello!"})
obj = dot_json('{"hello\\\\.world": "Hello!"}')
value = obj["hello\.world"]  # Hello!

 

That's all!

Tests

Run in the terminal from the parent directory:

python -m dotted.test.test_collection

Download details:

Author:  carlosescri
Source: https://github.com/carlosescri/DottedDict

License: MIT license

#python 

Access Lists and Dicts with Dotted Path Notation in Python with dotted
1.05 GEEK