通过保留不同值的键合并嵌套字典

时间:2013-11-22 19:00:54

标签: python python-3.x dictionary merge

我有两个嵌套字典列表,它们具有相同的键,但值不同:

d1 = {
    'distilled ': [{'water': '45'}, {'vodka': '9'}, {'vinegar': '7'}, {'beer': '6'}, {'alcohol': '5'}, {'whiskey': '5'}],
    'planted': [{'tree': '30'}, {'seed': '28'}, {'flower': '20'}, {'plant': '7'}, {'bomb': '4'}, {'garden': '2'}]
}

d2 = {
    'distilled  ': [{'water': '14'}, {'vinegar': '9'}, {'wine': '8'}, {'alcohol': '8'}, {'liquid': '7'}, {'whiskey': '6'}, {'beer': '5'}], 
    'planted ': [{'flower': '28'}, {'tree': '18'}, {'seed': '9'}, {'vegetable': '4'}, {'bush': '3'}, {'grass': '3'}, {'garden': '3'}]
}

我希望以保留值的方式合并它们,并仅合并嵌套字典中的键。结果如下:

{
    'distilled ': [('water', '45', '14'), ('vodka', '9'), ('vinegar', '7', '9'), ('beer', '6', '5'), ('alcohol',  '5'), ('whiskey', '5'), ('wine', '8')], 
    'planted': [('tree', '30', '18'), ('seed', '28', '9'), ('flower', '20', '7'), ('plant', '7'), ('bomb', '4'), ('garden', '2', '3')]
}

我尝试使用以下两种方法合并:

d_merged = { k: [ d1[k], d2_to_compare[k] ] for k in d1 }

但结果只显示了第一本字典的值。你对如何解决这个问题有任何想法吗?非常感谢你提前。

我不确定从这里采取哪种方式。非常感谢任何建议!非常感谢。

1 个答案:

答案 0 :(得分:0)

dict只有一个键值对不是一个好主意,但无论如何,我们可以这样做:

d1 = {
    'distilled': [{'water': '45'}, {'vodka': '9'}, {'vinegar': '7'}, {'beer': '6'},        {'alcohol': '5'}, {'whiskey': '5'}],
    'planted': [{'tree': '30'}, {'seed': '28'}, {'flower': '20'}, {'plant': '7'}, {'bomb': '4'}, {'garden': '2'}]
}

d2 = {
    'distilled': [{'water': '14'}, {'vinegar': '9'}, {'wine': '8'}, {'alcohol': '8'},   {'liquid': '7'}, {'whiskey': '6'}, {'beer': '5'}],
    'planted': [{'flower': '28'}, {'tree': '18'}, {'seed': '9'}, {'vegetable': '4'}, {'bush': '3'}, {'grass': '3'}, {'garden': '3'}]
}

d3 = {}

for k, v in d1.items():
    k1 = dict([d.items()[0] for d in d1[k]])
    k2 = dict([d.items()[0] for d in d2[k]])
    ret = []
    for d in (set(k1.keys()) | set(k2.keys())):
        ret.append((d, k1.get(d), k2.get(d)))
    d3[k] = ret

print d3