簡體   English   中英

將字典合並到一個具有唯一 ID 的字典列表中

[英]Merging dictionaries into one list of dictionaries on a unique id

我不知道如何最好地描述我所追求的 - 這不是字典的直接合並,因此將它們添加在一起或解壓縮它們是行不通的。 將我想要的內容與 pandas 合並進行比較可能更容易 - 加入一個公共鍵,這將根據輸入產生額外的列/行。

我從以下列表開始:

a = [{'GlobalID': '1e6afb53-9276-495a-81e0-1462b765fa67', 'aResult': 1}]
b = [{'GlobalID': '1e6afb53-9276-495a-81e0-1462b765fa67', 'bResult': 1}]
c = [{'GlobalID': '1e6afb53-9276-495a-81e0-1462b765fa67', 'cResult': 1}]
d = [{'GlobalID': '1e6afb53-9276-495a-81e0-1462b765fa67', 'dResult': 0},
  {'GlobalID': '43e405ee-a680-4958-a3c4-e64344a04786', 'dResult': 1},
  {'GlobalID': '2914fe6f-483c-479e-a1fa-2817737546bf', 'dResult': 0}
]

我想合並/組合它們,這樣我最終只得到唯一的 GlobalID 和任何相應的結果:

[
 {'GlobalID': '1e6afb53-9276-495a-81e0-1462b765fa67', 'aResult': 1, 'bResult': 1, 'cResult': 1, 'dResult': 0}, 
 {'GlobalID': '43e405ee-a680-4958-a3c4-e64344a04786', 'dResult': 1}, 
 {'GlobalID': '2914fe6f-483c-479e-a1fa-2817737546bf', 'dResult': 0}
]

有沒有一種簡單的方法可以做到這一點? 我很感激人們可以指出我的任何想法/資源。

謝謝!

lists = [a, b, c , d] # consider you have more than 4 lists
merged_dicts = dict({}) # create a dictionary to save the result
for l in lists: # loop on the lists
    for doc in l: # loop on the documents on each list
        GlobalID = doc['GlobalID'] # get the id of the document
        if GlobalID in merged_dicts: # check if we already found a doc with the same id
            old_doc = merged_dicts[GlobalID] # if yes we get the old merged doc
            for key in doc: # we loop over the contents of the new document
                old_doc[key] = doc[key] # we add the values to the doc result
            merged_dicts[GlobalID] = old_doc # and we change the result in the result dictionary
        else: # if not add the doc to the dictionary
            merged_dicts[GlobalID] = doc
merged_dicts.values()

Output:

[{'GlobalID': '43e405ee-a680-4958-a3c4-e64344a04786', 'dResult': 1},
 {'GlobalID': '1e6afb53-9276-495a-81e0-1462b765fa67',
  'aResult': 1,
  'bResult': 1,
  'cResult': 1,
  'dResult': 0},
 {'GlobalID': '2914fe6f-483c-479e-a1fa-2817737546bf', 'dResult': 0}]

暫無
暫無

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

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