How do I merge two dictionaries in a single expression in Python?
@lebyy▲ 0 net votes
Problem: I want to merge two dictionaries into a new dictionary. x = {'a': 1, 'b': 2} y = {'b': 3, 'c': 4} z = merge(x, y) >>> z {'a': 1, 'b': 3, 'c': 4} Whenever a key k is present in both dictionaries, only the value y[k] should be kept. Fix (from the top answer): How can I merge two Python dictionaries in a single expression? For dictionaries x and y , their shallowly-merged dictionary z takes values from y , replacing those from x . In Python 3.9.0 or greater (released 17 October 2020, PEP-584 , discussed here ): z = x | y In Python 3.5 or greater: z = {**x, **y} In Python…