MarieZ
MarieZ

Reputation: 35

Merge two dictionaries in python with lists as values

I have two dictionaries with lists as their values.
I want to merge them preserving unique item in the lists.
What I know is:

d1 = {'a':['aa','bb']}
d2 = {'a':['aa','cc'],'b':['xx','yy']}
d1.update(d2)
print d1
>>> {'a': ['aa', 'cc'], 'b': ['xx', 'yy']}

While I want to get

>>> {'a': ['aa', 'bb', 'cc'], 'b': ['xx', 'yy']}

What is the most efficient way of achieving this?

Upvotes: 1

Views: 91

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121416

Use sets instead of lists:

{k: set(d1.get(k, [])) | set(d2.get(k, [])) for k in d1.viewkeys() | d2}

For your sample input this produces:

>>> d1 = {'a':['aa','bb']}
>>> d2 = {'a':['aa','cc'],'b':['xx','yy']}
>>> {k: set(d1.get(k, [])) | set(d2.get(k, [])) for k in d1.viewkeys() | d2}
{'a': set(['aa', 'cc', 'bb']), 'b': set(['yy', 'xx'])}

This would be easier if you changed your input dictionaries to use sets for the values too.

If you must have lists and order doesn't matter, convert the sets back to lists:

{k: list(set(d1.get(k, [])) | set(d2.get(k, []))) for k in d1.viewkeys() | d2}

Upvotes: 4

Related Questions