因此,我不会先尝试解释,而是向您展示我拥有的和我想要的(这更容易):
我有什么:
dict_list = [
{'some': 1.2, 'key': 1.3, 'words': 3.9, 'label': 0},
{'other': 1.2, 'wordly': 1.3, 'words': 3.9, 'label': 1},
{'other': 10, 'work': 1.3, 'like': 3.9, 'label': 1},
]
我想从我拥有的东西中得到什么:
dict_dict = { "0":{'some': 1.2, 'key': 1.3, 'words': 3.9},
"1":{'other': 10, 'wordly': 1.3, 'work': 1.3, 'like': 3.9, 'words': 3.9},
}
解释:
所以,我想通过使用“label
”键作为新字典中的主键来创建一个字典。我还需要合并具有相同标签的词典。在此合并期间,如果存在重复键(如示例中的“other
”键),我需要保留最高值。
为什么我不在创建原始字典列表之前完成所有这些操作?
因为 dict_list
是一个 joblib(多处理)进程的结果。在进程之间共享一些对象会减慢多进程的速度。因此,我没有分享,而是决定在多核上运行繁重的工作,然后再进行组织。我不确定这种方法是否有任何帮助,但如果不进行测试我无法知道。
最佳答案
Counter 模块有很好的合并功能 a|b
,它加入字典保持较高的值。
from collections import Counter
dict_dict = {}
for dictionary in dict_list:
label = str(dictionary.pop('label'))
dict_dict[label] = dict_dict.get(label,Counter())|Counter(dictionary)
###If you don't need Counters, just convert back to dictionaries
dict_dict = {i:dict(v) for i,v in dict_dict.items()}
关于python - 如何使用内键 :value pair 将字典列表转换为字典字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64134499/