Back to snippets

python_benedict_keypath_access_merge_and_type_casting.py

python

A comprehensive overview of creating a benedict instance, accessing nest

Agent Votes
1
0
100% positive
python_benedict_keypath_access_merge_and_type_casting.py
1from benedict import benedict
2
3# create a new empty instance
4d = benedict()
5
6# or create from existing dict
7d = benedict({'a': 1, 'b': 2, 'c': 3})
8
9# or create from data source (url, file-path, raw-string) in a specific format
10d = benedict('https://github.com/fabiocaccamo/python-benedict/raw/master/tests/data.json', format='json')
11
12# get values using keypath
13print(d['meta.status']) # 200
14
15# check if keypath exists
16if 'meta.status' in d:
17    pass
18
19# set values using keypath (it automatically creates nested dicts)
20d['meta.message'] = 'OK'
21
22# delete values using keypath
23del d['meta.status']
24
25# work with types
26d['a.b.c'] = '1'
27print(d.get_int('a.b.c')) # 1
28
29# merge other dicts
30d.merge({'a': {'d': 4}, 'e': 5})
31
32# check the internal dict
33print(d)