在 2 个嵌套字典之间合并并获得单个字典

Merge between 2 nested dictionaries and obtain single dict

我知道有类似的问题。我尝试搜索示例和答案,但没有明确的解决方案。我被困在这个。我有 2 个嵌套字典,我想将它合并到单个字典中。它是 JSON 版本,但 python 中的 运行 也可以。

x = {'folders': [
{'id': 124, 'name': 'Leads', 'totalBlacklisted': 0, 'uniqueSubscribers': 0, 'totalSubscribers': 0}, 
{'id': 123, 'name': 'Alumni', 'totalBlacklisted': 0, 'uniqueSubscribers': 0, 'totalSubscribers': 0}, 
]}
y = {'folders':[{'id': 124,'name':'Leads'}, {'id': 121,'name': 'Member'},{'id':123,'name':'Alumni'}]}

我想要的:

result = {'folders': [
{'id': 124, 'name': 'Leads', 'totalBlacklisted': 0, 'uniqueSubscribers': 0, 'totalSubscribers': 0}, 
{'id': 123, 'name': 'Alumni', 'totalBlacklisted': 0, 'uniqueSubscribers': 0, 'totalSubscribers': 0},
{'id': 121, 'name': 'Member'} 
]}

请帮帮我

您可以简单地添加它们并在字典上添加条件,以防出现冲突的 ID:

x['folders']+[dic for dic in y['folders'] if dic['id'] not in [dic['id'] for dic in x['folders']]]

结果:

[{'id': 124,
  'name': 'Leads',
  'totalBlacklisted': 0,
  'uniqueSubscribers': 0,
  'totalSubscribers': 0},
 {'id': 123,
  'name': 'Alumni',
  'totalBlacklisted': 0,
  'uniqueSubscribers': 0,
  'totalSubscribers': 0},
 {'id': 121, 'name': 'Member'}]

一般的想法是用 groupby 将我们认为相同的元素分组到元组 (x[id] , x[name]) 中,然后将每组除我们的键之外的所有多余元素与 ChainMap.

from pprint import pprint
from itertools import groupby
from collections import ChainMap

a = {
    'folders': [
        { 'id': 124, 'name': 'Leads',  'totalBlacklisted': 0, 'uniqueSubscribers': 0, 'totalSubscribers': 0 }, 
        { 'id': 123, 'name': 'Alumni', 'totalBlacklisted': 0, 'uniqueSubscribers': 0, 'totalSubscribers': 0 }, 
    ]
}

b = {
    'folders': [
        { 'id': 124, 'name': 'Leads'  },
        { 'id': 121, 'name': 'Member' },
        { 'id': 123, 'name': 'Alumni' }
    ]
}

def key(x):
    return (x['id'], x['name'])

def merge(a, b, key):
    c = a + b
    groups = groupby(sorted(c, key=key), key=key)
    merged = [dict(ChainMap(*g)) for _, g in groups]
    return merged
pprint({'folders': merge(a['folders'], b['folders'], key=key)})
> {'folders': [{'id': 121, 'name': 'Member'},
               {'id': 123,
                'name': 'Alumni',
                'totalBlacklisted': 0,
                'totalSubscribers': 0,
                'uniqueSubscribers': 0},
               {'id': 124,
                'name': 'Leads',
                'totalBlacklisted': 0,
                'totalSubscribers': 0,
                'uniqueSubscribers': 0}]}

如果你想查看 groupby 的输出,运行 这个修改后的合并函数:

def merge(a, b, key):
    c = a + b
    groups = groupby(sorted(c, key=key), key=key)
    merged = [(k, list(g)) for k, g in groups]
    return merged