Dennis Dmitriev | de847d9 | 2017-06-26 18:58:05 +0300 | [diff] [blame] | 1 | |
| 2 | def get_nested_key(data, path=None): |
| 3 | if type(path) is not list: |
| 4 | raise("Use 'list' object with key names for 'path'") |
| 5 | for key in path: |
| 6 | value = data.get(key, None) |
| 7 | if value: |
| 8 | data = value |
| 9 | else: |
| 10 | return None |
| 11 | return data |
| 12 | |
| 13 | |
Dennis Dmitriev | 30dfb89 | 2017-06-29 20:58:11 +0300 | [diff] [blame^] | 14 | def create_nested_key(data, path=None, value=None): |
| 15 | if type(data) is not dict: |
| 16 | raise("Use 'dict' object for 'data'") |
| 17 | if type(path) is not list: |
| 18 | raise("Use 'list' object with key names for 'path'") |
| 19 | for key in path[:-1]: |
| 20 | if key not in data: |
| 21 | data[key] = {} |
| 22 | data = data[key] |
| 23 | data[path[-1]] = value |
| 24 | |
| 25 | |
Dennis Dmitriev | de847d9 | 2017-06-26 18:58:05 +0300 | [diff] [blame] | 26 | def remove_nested_key(data, path=None): |
| 27 | if type(path) is not list: |
| 28 | raise("Use 'list' object with key names for 'path'") |
| 29 | |
| 30 | # Remove the value from the specified key |
| 31 | val = get_nested_key(data, path[:-1]) |
| 32 | val[path[-1]] = None |
| 33 | |
| 34 | # Clear parent keys if empty |
| 35 | while path: |
| 36 | val = get_nested_key(data, path) |
| 37 | if val: |
| 38 | # Non-empty value, nothing to do |
| 39 | return |
| 40 | else: |
| 41 | get_nested_key(data, path[:-1]).pop(path[-1]) |
| 42 | path = path[:-1] |
| 43 | |
| 44 | |