我有一个字典列表,我必须在其中合并具有相同键的值。我已经尝试过,但是没有得到预期的格式。谁能告诉我该怎么做?
dict_list=[{'fl_metric': ('randomforest', 0.8), 'accuracy': ('randomforest', 0.9)}, {'fl_metric': ('sgdclassifier', 0.4), 'accuracy': ('sgdclassifier', 0.5)}]
输出应为:
d = {'accuracy': [('randomforest', 0.4), ('sgdclassifier', 0.5)],
'f1_metric': [('randomforest', 0.8), ('sgdclassifier', 0.9)]}
答案 0 :(得分:1)
使用collections.defaultdict
例如:
from collections import defaultdict
dict_list=[{'fl_metric': ('randomforest', 0.8), 'accuracy': ('randomforest', 0.9)}, {'fl_metric': ('sgdclassifier', 0.4), 'accuracy': ('sgdclassifier', 0.5)}]
result = defaultdict(list)
for i in dict_list:
for k, v in i.items():
result[k].append(v)
print(result)
# --> defaultdict(<type 'list'>, {'fl_metric': [('randomforest', 0.8), ('sgdclassifier', 0.4)], 'accuracy': [('randomforest', 0.9), ('sgdclassifier', 0.5)]})
或使用setdefault
例如:
result = {}
for i in dict_list:
for k, v in i.items():
result.setdefault(k, []).append(v)
print(result)
# --> {'fl_metric': [('randomforest', 0.8), ('sgdclassifier', 0.4)], 'accuracy': [('randomforest', 0.9), ('sgdclassifier', 0.5)]}