<p>我会使用一个helper函数:</p>
<pre><code>from itertools import groupby
from operator import itemgetter
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('_', 2)[1]))
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('_', 2)[-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_') and not k.startswith('b_')}
s_values = extract_keys(abc, 's')
if s_values is not None:
xyz['s'] = s_values
b_values = extract_keys(abc, 'b')
if b_values is not None:
xyz['b'] = b_values
</code></pre>
<p>这会将<code>abc</code>示例输入转换为:</p>
<pre><code>>>> pprint(xyz)
{'b': [{'id': '9', 'name': 'henrik'}],
'id': '1',
'name': 'peter',
's': [{'id': '2', 'name': 'melisa'}, {'id': '4', 'name': 'graham'}],
'type': 'insecure'}
</code></pre>