tools (common/data_format): added dict2iterdict to yield dictionary from serialised complex values

This commit is contained in:
Goffi 2017-02-16 00:40:50 +01:00
commit 84fd46d62c

View file

@ -18,10 +18,10 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
""" 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 @@ def dict2iter(name, dict_, pop=False):
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