簡體   English   中英

如何使用內部鍵:值對將字典列表轉換為字典字典

[英]How to convert list of dictionaries into a dictionary of dictionaries by using inner key:value pair

因此,與其嘗試先解釋事情,不如向您展示我擁有的和想要的(這更容易):

我擁有的:

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()}

簡單的 pisy:

dict_of_dicts = {i:item for  i,item in enumerate(list_of_dicts)}

如果你堅持在鍵中使用字符串:

dict_of_dicts = {str(i):item for  i,item in enumerate(list_of_dicts)}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM