<p>我把它改进了一点,这样它就更灵活了。在</p>
<pre><code>def extract_keys(mapping, prefix):
prefix = "{}_".format(prefix)
# test for the `.._count` key first, if it's not there, bail out early
if prefix + "count" not in mapping:
return None
# find all matching keys, split out the counter for sorting and grouping
keys = [(k, int(k.split("_", -1)[-2])) for k in mapping if k.startswith(prefix) and k != prefix + "count"]
keys.sort(key=itemgetter(1))
# group keys on the counter, then generate a dictionary per counter value
return [{k[0].split("_", -1)[-1]: mapping[k[0]] for k in group} for c, group in groupby(keys, itemgetter(1))]
</code></pre>
<p>考虑下面的字典。在</p>
^{pr2}$
<p>使用该函数可以创建新词典或就地转换现有词典:</p>
<pre><code>xyz = {k: v for k, v in abc.iteritems() if not k.startswith('s_a') and not k.startswith('b_')}
s_values = extract_keys(abc, 's_a')
if s_values is not None:
xyz['s_a'] = s_values
b_values = extract_keys(abc, 'b')
if b_values is not None:
xyz['b'] = b_values
</code></pre>
<p>转化后的输出为:</p>
<pre><code>print xyz
{'b': [{'id': '9', 'name': 'henrik'}],
'id': '1',
'name': 'peter',
's_a': [{'id': '2', 'name': 'melisa'}, {'id': '4', 'name': 'graham'}],
'type': 'insecure'}
</code></pre>