# HG changeset patch # User Goffi # Date 1487202050 -3600 # Node ID f67434fd88d26f01a3a432f3f4f052c64d8e0a39 # Parent 6a004a22dd9eeac94a8979eecd12d39a2e3430e4 tools (common/data_format): added dict2iterdict to yield dictionary from serialised complex values diff -r 6a004a22dd9e -r f67434fd88d2 src/tools/common/data_format.py --- a/src/tools/common/data_format.py Mon Feb 13 20:59:09 2017 +0100 +++ b/src/tools/common/data_format.py Thu Feb 16 00:40:50 2017 +0100 @@ -18,10 +18,10 @@ # along with this program. If not, see . """ tools common to backend and frontends """ +# FIXME: json may be more appropriate than manual serialising like done here from sat.core import exceptions - def dict2iter(name, dict_, pop=False): """iterate into a list serialised in a dict @@ -54,6 +54,24 @@ else: idx += 1 +def dict2iterdict(name, dict_, extra_keys, pop=False): + """like dict2iter but yield dictionaries + + params are like in [dict2iter], extra_keys is used for extra dict keys. + e.g. dict2iterdict(comments, mb_data, ('node', 'service')) will yield dicts like: + {u'comments': u'value1', u'node': u'value2', u'service': u'value3'} + """ + # FIXME: this format seem overcomplicated, it may be more appropriate to use json here + if pop: + get=lambda d,k: d.pop(k) + else: + get=lambda d,k: d[k] + for idx, main_value in enumerate(dict2iter(name, dict_, pop=pop)): + ret = {name: main_value} + for k in extra_keys: + ret[k] = get(dict_, u'{}{}_{}'.format(name, (u'#' + unicode(idx)) if idx else u'', k)) + yield ret + def iter2dict(name, iter_, dict_=None, check_conflict=True): """Fill a dict with values from an iterable