comparison src/tools/common/data_format.py @ 2153:f67434fd88d2

tools (common/data_format): added dict2iterdict to yield dictionary from serialised complex values
author Goffi <goffi@goffi.org>
date Thu, 16 Feb 2017 00:40:50 +0100
parents c8e561a5b2b6
children 8b37a62336c3
comparison
equal deleted inserted replaced
2152:6a004a22dd9e 2153:f67434fd88d2
16 16
17 # You should have received a copy of the GNU Affero General Public License 17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. 18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 19
20 """ tools common to backend and frontends """ 20 """ tools common to backend and frontends """
21 # FIXME: json may be more appropriate than manual serialising like done here
21 22
22 from sat.core import exceptions 23 from sat.core import exceptions
23
24 24
25 def dict2iter(name, dict_, pop=False): 25 def dict2iter(name, dict_, pop=False):
26 """iterate into a list serialised in a dict 26 """iterate into a list serialised in a dict
27 27
28 name is the name of the key. 28 name is the name of the key.
51 yield get(dict_,u'{}#{}'.format(name, idx)) 51 yield get(dict_,u'{}#{}'.format(name, idx))
52 except KeyError: 52 except KeyError:
53 return 53 return
54 else: 54 else:
55 idx += 1 55 idx += 1
56
57 def dict2iterdict(name, dict_, extra_keys, pop=False):
58 """like dict2iter but yield dictionaries
59
60 params are like in [dict2iter], extra_keys is used for extra dict keys.
61 e.g. dict2iterdict(comments, mb_data, ('node', 'service')) will yield dicts like:
62 {u'comments': u'value1', u'node': u'value2', u'service': u'value3'}
63 """
64 # FIXME: this format seem overcomplicated, it may be more appropriate to use json here
65 if pop:
66 get=lambda d,k: d.pop(k)
67 else:
68 get=lambda d,k: d[k]
69 for idx, main_value in enumerate(dict2iter(name, dict_, pop=pop)):
70 ret = {name: main_value}
71 for k in extra_keys:
72 ret[k] = get(dict_, u'{}{}_{}'.format(name, (u'#' + unicode(idx)) if idx else u'', k))
73 yield ret
56 74
57 def iter2dict(name, iter_, dict_=None, check_conflict=True): 75 def iter2dict(name, iter_, dict_=None, check_conflict=True):
58 """Fill a dict with values from an iterable 76 """Fill a dict with values from an iterable
59 77
60 name is used to serialise iter_, in the same way as in [dict2iter] 78 name is used to serialise iter_, in the same way as in [dict2iter]