Home > other >  How do I combine two dictionaries with similar keys but different values?
How do I combine two dictionaries with similar keys but different values?

Time:10-18

For example, I have

a = {'bob': [1, 2], 'bill': [3, 4], 'steve': [1]}

and I want to add this to another dictionary

b = {'bob': [4], 'bill': [7]}

to create

b = {'bob': [1, 2, 4], 'bill': [3, 4, 7], 'steve': [1]}

I tried looping through a and adding the list to the values of the list from b to a, but it isn't working with basic list addition methods. Thanks in advance.

CodePudding user response:

Something like this should work:

def add_dicts(a, b):
    return {
        k: a.get(k, [])   b.get(k, [])
        for k in a | b
    }


result = add_dicts(a, b)

CodePudding user response:

Use a dictionary comprehension, iterating over a union of the keys from both dictionaries. Using get will let us default to an empty list if either dictionary lacks the key in question. This avoids a KeyError exception.

>>> {k: a.get(k, [])   b.get(k, []) for k in a.keys() | b.keys()}
{'steve': [1], 'bob': [1, 2, 4], 'bill': [3, 4, 7]}

Without explicitly calling keys:

{k: a.get(k, [])   b.get(k, []) for k in a | b}

CodePudding user response:

That code will merge them in the way you want:

a = {'bob': [1, 2], 'bill': [3, 4], 'steve': [1]}
b = {'bob': [4], 'bill': [7]}

def merge(a, b):
    for k, l in a.items():
        b[k] = l    b.get(k, [])

merge(a, b)
print(b)
# {'bob': [1, 2, 4], 'bill': [3, 4, 7], 'steve': [1]}

CodePudding user response:

c = {key: a.get(key,[])   b.get(key, [])  for key in a|b}

It's unclear what you want to do if the lists are intersecting

So if you want only new items then this

c = {key: list(set(a.get(key,[])) | set(b.get(key, [])))  for key in a|b}
  • Related