在 python 2.2 中:
stat2 = {}
for s in stat:
for c in s.values():
for k, v in c.items():
if k in stat2:
stat2[k] += v
else:
stat2[k] = v # perhaps copying here
stat2
{'asian': ['japan', 'china'],
'europe': ['germany', 'england', 'french', 'netherland']}
如果您使用的是 python > 2.4,则可以只使用 defaultdict:
from collections import defaultdict
stat2 = defaultdict(list)
for s in stat:
for c in s.values():
for k, v in c.items():
stat2[k] += v
stat2
defaultdict(<type 'list'>, {'europe': ['germany', 'england', 'french', 'netherland'], 'asian': ['japan', 'china']})
如果你真的想要:
{'state': [dict(stat2)]}
{'state': [{'asian': ['japan', 'china'],
'europe': ['germany', 'england', 'french', 'netherland']}]}
考虑升级你的 python 版本,2.2 于 2001 年发布......!