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

Neuron
  • 5,141
  • 5
  • 38
  • 59
NicolaiF
  • 1,283
  • 1
  • 20
  • 44

1 Answers1

17
dict2.update(dict1)

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

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Wow, that was quick. That seems to do the trick! – NicolaiF Oct 28 '16 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 Oct 28 '16 at 14:26