user2962024
user2962024

Reputation: 317

Merging nested dictionaries by keys preserving different values

I have two list of nested dictionaries with the same keys, but different values:

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

and

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

I want to merge them in a way that preserves the values and merges only the keys in the nested dictionaries. So that the outcome would look like:

{
    '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')]
}

I tried merging the two using:

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

but the in the outcome only the values of the first dictionary are presented, obviously. Do you have any ideas on how to fix this? Thank you very much in advance.

I am not sure which way to take from here. Would really appreciate any suggestions! Thanks a lot.

Upvotes: 0

Views: 196

Answers (1)

PasteBT
PasteBT

Reputation: 2198

dict only has one key-value pair is not a good idea, but anyway, we can work out like this:

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

Upvotes: 0

Related Questions