私信  •  关注

Stephen Cowley

Stephen Cowley 最近创建的主题
Stephen Cowley 最近回复了
6 年前
回复了 Stephen Cowley 创建的主题 » python列表的dict到dict列表的dict

我建议使用defaultdict

from collections import defaultdict

new_dict = defaultdict(list) # New entries will automatically be empty lists
for data_dict in old_list: # Cycle through your old data structure
    new_dict[data_dict['name']].append(data_dict) # Append to the list in the defaultdict with the key testname

这就产生了:

defaultdict(list,
        {'test14': [{'accuracy': 0.04584040881114014,
           'epoch': 0,
           'loss': 3.908684137519228,
           'name': 'test14',
           'val_accuracy': 0.1878172606229782,
           'val_loss': 3.8432216644287114},
          {'accuracy': 0.1612903245539738,
           'epoch': 1,
           'loss': 3.8308442072066873,
           'name': 'test14',
           'val_accuracy': 0.1878172606229782,
           'val_loss': 3.4720854759216313}],
         'test15': [{'accuracy': 0.056027164736506485,
           'epoch': 0,
           'loss': 3.9064058800099866,
           'name': 'test15',
           'val_accuracy': 0.1878172606229782,
           'val_loss': 3.8064255714416495},
          {'accuracy': 0.16129032566713356,
           'epoch': 1,
           'loss': 3.7856348285448367,
           'name': 'test15',
           'val_accuracy': 0.1878172606229782,
           'val_loss': 3.5590925216674805}]})