Skip to content

Instantly share code, notes, and snippets.

@yuyosy
Created January 18, 2021 04:46
Show Gist options
  • Save yuyosy/5d692b0c5779a7928722b42631557625 to your computer and use it in GitHub Desktop.
Save yuyosy/5d692b0c5779a7928722b42631557625 to your computer and use it in GitHub Desktop.
import re
from functools import reduce
def set_attr(obj, keystr, value, delimiter='.'):
key_list = keystr.split(delimiter)
o, k = _set_parse_keystr(obj, key_list)
o[k] = value
print(' -+', o[k])
return obj
def _set_parse_keystr(obj, key_list):
# print('|',key_list)
key = key_list[0]
if len(key_list) > 1:
#print('|0',obj, key_list)
if obj.get(key) is None:
obj[key] = {}
return _set_parse_keystr(obj.get(key), key_list[1:])
print('|1',obj, key_list)
if obj.get(key) is None:
obj[key] = None
return obj, key
def get_attr(obj, keystr, delimiter='.'):
key_list = keystr.split(delimiter)
a = reduce(lambda el, key: _get_parse_keystr(el, key), key_list, obj)
print(' ->', a)
return a
def _get_parse_keystr(obj, keystr):
if re.search(r'(.*)\[\d?\]$', keystr):
key, index, _ = re.split('\[|\]', keystr)
return obj.get(key)[int(index)]
else:
return obj.get(keystr)
if __name__ == '__main__':
o = {
'a': {
'bb': {
'ccc': 123
},
'bb2': 14,
'bb3': {
'b3c1': '@b3c1',
'b3c2': '@b3c2',
}
},
'aa': [1,2,3,4,5],
'aad': [
{'aad0':None},
{'aad1-1':'*1-1'},
{'aad2-1':'*2-1','aad2-2':'*2-2'},
{'aad3-1':'*3-1'}
]
}
print(o)
get_attr(o, 'a.bb.ccc')
get_attr(o, 'a.bb2')
get_attr(o, 'a.bb3')
set_attr(o, 'a.bb3.b3c1', '@@@')
set_attr(o, 'a.b0.j.k.l', '#0jkl')
get_attr(o, 'aa[2]')
get_attr(o, 'aad[1].aad1-1')
get_attr(o, 'aad[2].aad2-2')
print(o)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment