118 if key in keys: |
118 if key in keys: |
119 new_key = keys[key] |
119 new_key = keys[key] |
120 result[new_key] = value |
120 result[new_key] = value |
121 |
121 |
122 return result |
122 return result |
|
123 |
|
124 |
|
125 def split(target): |
|
126 """Takes a dictionary and splits it into single-valued dicts |
|
127 |
|
128 If there are any values in target that are a list it is split up |
|
129 into a new dictionary instead. |
|
130 |
|
131 >>> split({}) |
|
132 [{}] |
|
133 >>> split({'foo':'bar'}) |
|
134 [{'foo': 'bar'}] |
|
135 >>> split({'foo':'bar', 'bar':'baz'}) |
|
136 [{'foo': 'bar', 'bar': 'baz'}] |
|
137 >>> split({'foo':'bar', 'bar':['one', 'two']}) |
|
138 [{'foo': 'bar', 'bar': 'one'}, {'foo': 'bar', 'bar': 'two'}] |
|
139 >>> split({'foo':'bar', 'bar':['one', 'two'], 'baz': ['three', 'four']}) |
|
140 [{'bar': 'one', 'foo': 'bar', 'baz': 'three'}, |
|
141 {'bar': 'two', 'foo': 'bar', 'baz': 'three'}, |
|
142 {'bar': 'one', 'foo': 'bar', 'baz': 'four'}, |
|
143 {'bar': 'two', 'foo': 'bar', 'baz': 'four'}] |
|
144 """ |
|
145 |
|
146 result = [{}] |
|
147 |
|
148 for key, values in target.iteritems(): |
|
149 # Make the value a list if it's not |
|
150 if not isinstance(values, list): |
|
151 values = [values] |
|
152 |
|
153 tmpresult = [] |
|
154 |
|
155 # Iterate over all we gathered so far |
|
156 for filter in result: |
|
157 for value in values: |
|
158 # Create a new dict from the current filter |
|
159 newdict = dict(filter) |
|
160 |
|
161 # And create a new dict that also has the current key/value pair |
|
162 newdict[key] = value |
|
163 tmpresult.append(newdict) |
|
164 |
|
165 # Update the result for the next iteration |
|
166 result = tmpresult |
|
167 |
|
168 return result |