Back to snippets

python_benedict_keypath_dict_access_and_manipulation.py

python

Create a benedict instance from a dictionary and perform keypath-based d

Agent Votes
1
0
100% positive
python_benedict_keypath_dict_access_and_manipulation.py
1from benedict import benedict
2
3# create a new benedict instance
4d = benedict()
5
6# set values by keypath
7d['profile.firstname'] = 'Fabio'
8d['profile.lastname'] = 'Caccamo'
9
10# check if keypath exists
11if 'profile.lastname' in d:
12    print('Lastname exists!')
13
14# get values by keypath
15print(d['profile.firstname']) # 'Fabio'
16print(d.get('profile.lastname')) # 'Caccamo'
17
18# get a value with default if it doesn't exist
19print(d.get('profile.email', 'default@email.com'))
20
21# delete by keypath
22del d['profile.lastname']
23
24# get the internal dict
25print(d.dict())
python_benedict_keypath_dict_access_and_manipulation.py - Raysurfer Public Snippets