From 3337750def08478d4fa523932f7d262501642239 Mon Sep 17 00:00:00 2001 From: Goffi Date: Sun, 25 Sep 2016 19:16:25 +0200 Subject: [PATCH] core (tools/common): added getSubDict method in data_format to get sub dictionary from serialised one --- src/tools/common/data_format.py | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/tools/common/data_format.py b/src/tools/common/data_format.py index f4d540e6..3e0a5e27 100644 --- a/src/tools/common/data_format.py +++ b/src/tools/common/data_format.py @@ -31,7 +31,7 @@ def dict2iter(name, dict_, pop=False): iteration stop at first missing increment Empty values are possible @param name(unicode): name of the key - @param mb_data (dict): dictionary with the serialised list + @param dict_(dict): dictionary with the serialised list @param pop(bool): if True, remove the value from dict @return iter: iterate through the deserialised list """ @@ -79,3 +79,24 @@ def iter2dict(name, iter_, dict_=None, check_conflict=True): raise exceptions.ConflictError dict_[key] = value return dict + +def getSubDict(name, dict_, sep=u'_'): + """get a sub dictionary from a serialised dictionary + + look for keys starting with name, and create a dict with it + eg.: if "key" is looked for, {'html': 1, 'key_toto': 2, 'key_titi': 3} will return: + {None: 1, toto: 2, titi: 3} + @param name(unicode): name of the key + @param dict_(dict): dictionary with the serialised list + @param sep(unicode): separator used between name and subkey + @return iter: iterate through the deserialised items + """ + for k,v in dict_.iteritems(): + if k.startswith(name): + if k == name: + yield None, v + else: + if k[len(name)] != sep: + continue + else: + yield k[len(name)+1:], v