Merging Dicts in Python 2 and 3

2018-01-29 | #python, #webdev

From JavaScript we are used to operations like:

var newDict = _.extend({a : 'a'}, {b : 'b'});

=> {a : 'a', b : 'b'}

Since we tend to use dicts in Python quite a lot as well, how do we do this elegantly in Python?

There are two answers to this question, depending on your version of Python:

# python < 3.5

# shallow copy of first

merged_dict = first_dict.copy()

merged_dict.update(second_dict)

# deep copy of first

import copy

merged_dict = copy.deepcopy(first_dict)

merged_dict.update(second_dict)

or

# python >= 3.5

merged_dict = {**first_dict, **second_dict}