n00bprogrammer22 n00bprogrammer22 - 20 days ago 8
Python Question

Merging dictionaries python without repeating keys

I'm writing a function where I'm trying to merge together two dictionaries (referred to as databases) without repeating any of the keys or modifying the originals. I think I'm close but I'm currently getting the error 'db1' is not defined even though it is one of the parameters of the function. Here is an example of two dictionaries and what I need them to look like merged

d1

{'Leonardo da Vinci': [('Mona Lisa', 1503, 76.8, 53.0, 'oil paint', 'France'),
('The Last Supper', 1495, 460.0, 880.0, 'tempera', 'Italy')]}


d2

{'Pablo Picasso' : [('Guernica', 1937, 349.0, 776.0, 'oil paint', 'Spain')],
'Leonardo da Vinci' : [("Portrait of Isabella d'Este", 1499, 63.0, 46.0, 'chalk', 'France'),
('The Last Supper', 1495, 460.0, 880.0, 'tempera', 'Italy')]}


merged

{'Pablo Picasso' : [('Guernica', 1937, 349.0, 776.0, 'oil paint', 'Spain')],
'Leonardo da Vinci': [('Mona Lisa', 1503, 76.8, 53.0, 'oil paint', 'France'),
("Portrait of Isabella d'Este", 1499, 63.0, 46.0, 'chalk', 'France'),
('The Last Supper', 1495, 460.0, 880.0, 'tempera', 'Italy')]}


As you can see the key "Leonardo da Vinci" appears in both dictionaries but should only appear once in the merged dictionary. Thanks to anyone who can help. Here is my current code:

def merge_databases (db1,db2):
ds = [db1, db2]
d = {}
for k in db1.iterkeys():
d[k] = tuple(d[k] for d in ds)

Answer

I think that is what you need:

def merge_databases(db1, db2):
    d = {}
    for key in db1.keys() | db2.keys():
        d[key] = db1.get(key, []) + db2.get(key, [])    
    return d

or even:

def merge_databases(db1, db2):
    return {key: db1.get(key, []) + db2.get(key, []) 
            for key in db1.keys() | db2.keys()}
Comments