diff options
author | Étienne Loks <etienne.loks@iggdrasil.net> | 2018-10-31 13:57:07 +0100 |
---|---|---|
committer | Étienne Loks <etienne.loks@iggdrasil.net> | 2018-10-31 13:57:07 +0100 |
commit | caab0d3b903f7aba08edc007dd9e595577a9777a (patch) | |
tree | 95cd521ca0d79a5b04625462af93fbe387bb8436 /ishtar_common/utils.py | |
parent | ca0802e71b25393a849762c305880b42b676148e (diff) | |
download | Ishtar-caab0d3b903f7aba08edc007dd9e595577a9777a.tar.bz2 Ishtar-caab0d3b903f7aba08edc007dd9e595577a9777a.zip |
Move dict data
Diffstat (limited to 'ishtar_common/utils.py')
-rw-r--r-- | ishtar_common/utils.py | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/ishtar_common/utils.py b/ishtar_common/utils.py index fb09c5876..4f968af31 100644 --- a/ishtar_common/utils.py +++ b/ishtar_common/utils.py @@ -163,6 +163,59 @@ def update_data(data_1, data_2): return res +def move_dict_data(data, key1, key2): + """ + Move key1 value to key2 value in a data dict + :param data: data dict (with subdicts) + :param key1: key to move (with __ notation for hierarchy - begining with + "data__") + :param key2: target key (with __ notation for hierarchy - begining with + "data__") + :return: result data + """ + keys1 = key1.split('__') + keys2 = key2.split('__') + value = data + for idx, key in enumerate(keys1): + if not idx: + if key != 'data': + return data + continue + if key not in value: + return data + if idx == (len(keys1) - 1): # last + value = value.pop(key) # remove from data + else: + value = value[key] + + new_value = data + for idx, key in enumerate(keys2): + if not idx: + if key != 'data': + return data + continue + if idx == (len(keys2) - 1): # last + new_value[key] = value + else: + if key not in new_value: + new_value[key] = {} + new_value = new_value[key] + return data + + +def clean_empty_data(data): + """ + Clean empty branches of a data dict + """ + for key in data.keys(): + if data[key] in [{}, None, u""]: + data.pop(key) + continue + if isinstance(data[key], dict): + data[key] = clean_empty_data(data[key]) + return data + + class MultiValueDict(BaseMultiValueDict): def get(self, *args, **kwargs): v = super(MultiValueDict, self).getlist(*args, **kwargs) |