28

I have two dictionaries that I want the union of so that each value from the first dictionary is kept and all the key:value pairs from the second dictionary is added to the new dictionary, without overriding the old entries.

dict1 = {'1': 1, '2': 1, '3': 1, '4': 1}
dict2 = {'1': 3, '5': 0, '6': 0, '7': 0}

where the function dictUnion(dict1, dict2) returns

{'1': 1, '2': 1, '3': 1, '4': 1, '5': 0, '6': 0, '7': 0}

I can, and have done it by using simple loops, this is pretty slow though when operating on large dictionaries. A faster more "pythonic" way would be appreciated

1
  • That page has some great info, thanks alot for sharing!
    – NicolaiF
    Commented Oct 28, 2016 at 14:28

1 Answer 1

17
dict2.update(dict1)

This keeps all values from dict1 (it overwrites the same keys in dict2 if they exist).

2
  • Wow, that was quick. That seems to do the trick!
    – NicolaiF
    Commented Oct 28, 2016 at 14:25
  • 5
    @NicolaiF Note that this doesn't return the modified dictionary. There's a lot of information in the duplicate question in the comment to your answer, so I won't post it here.
    – brianpck
    Commented Oct 28, 2016 at 14:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.