comparison src/tools/common/data_format.py @ 2079:c8e561a5b2b6

core (tools/common): added getSubDict method in data_format to get sub dictionary from serialised one
author Goffi <goffi@goffi.org>
date Sun, 25 Sep 2016 19:16:25 +0200
parents 2daf7b4c6756
children f67434fd88d2
comparison
equal deleted inserted replaced
2078:3a0a7e5cef49 2079:c8e561a5b2b6
29 Serialisation is done with [name] [name#1] [name#2] and so on 29 Serialisation is done with [name] [name#1] [name#2] and so on
30 e.g.: if name is 'group', keys are group, group#1, group#2, ... 30 e.g.: if name is 'group', keys are group, group#1, group#2, ...
31 iteration stop at first missing increment 31 iteration stop at first missing increment
32 Empty values are possible 32 Empty values are possible
33 @param name(unicode): name of the key 33 @param name(unicode): name of the key
34 @param mb_data (dict): dictionary with the serialised list 34 @param dict_(dict): dictionary with the serialised list
35 @param pop(bool): if True, remove the value from dict 35 @param pop(bool): if True, remove the value from dict
36 @return iter: iterate through the deserialised list 36 @return iter: iterate through the deserialised list
37 """ 37 """
38 if pop: 38 if pop:
39 get=lambda d,k: d.pop(k) 39 get=lambda d,k: d.pop(k)
77 key = u'{}#{}'.format(name, idx) 77 key = u'{}#{}'.format(name, idx)
78 if check_conflict and key in dict_: 78 if check_conflict and key in dict_:
79 raise exceptions.ConflictError 79 raise exceptions.ConflictError
80 dict_[key] = value 80 dict_[key] = value
81 return dict 81 return dict
82
83 def getSubDict(name, dict_, sep=u'_'):
84 """get a sub dictionary from a serialised dictionary
85
86 look for keys starting with name, and create a dict with it
87 eg.: if "key" is looked for, {'html': 1, 'key_toto': 2, 'key_titi': 3} will return:
88 {None: 1, toto: 2, titi: 3}
89 @param name(unicode): name of the key
90 @param dict_(dict): dictionary with the serialised list
91 @param sep(unicode): separator used between name and subkey
92 @return iter: iterate through the deserialised items
93 """
94 for k,v in dict_.iteritems():
95 if k.startswith(name):
96 if k == name:
97 yield None, v
98 else:
99 if k[len(name)] != sep:
100 continue
101 else:
102 yield k[len(name)+1:], v