简体   繁体   English

将字典合并到一个具有唯一 ID 的字典列表中

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

I'm not sure how to best describe what I'm after - it's not exactly a straight merge of dictionaries so adding them together or unpacking them isn't going to work.我不知道如何最好地描述我所追求的 - 这不是字典的直接合并,因此将它们添加在一起或解压缩它们是行不通的。 It's probably easier to compare what I want to a pandas merge - join on a common key which will result in additional columns/rows depending on the inputs.将我想要的内容与 pandas 合并进行比较可能更容易 - 加入一个公共键,这将根据输入产生额外的列/行。

I am starting with the below lists:我从以下列表开始:

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}
]

And I want to merge/combine them such that I end up only with the unique GlobalIDs and any corresponding results:我想合并/组合它们,这样我最终只得到唯一的 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}
]

Is there a straightforward way of doing this?有没有一种简单的方法可以做到这一点? I'd appreciate any ideas/resources people can point me to.我很感激人们可以指出我的任何想法/资源。

Thanks!谢谢!

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: 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