HOW TO MERGE TWO DICTIONARIES IN A SINGLE EXPRESSION?

How to merge two dictionaries in a single expression?

For dictionaries x and y, z becomes a merged dictionary with values from y replacing those from x.
In Python 3.5 or greater, :
z = {**x, **y}
In Python 2, (or 3.4 or lower) write a function:
def merge_two_dicts(x, y):
z = x.copy() # start with x’s keys and values
z.update(y) # modifies z with y’s keys and values & returns None
return z
and
z = merge_two_dicts(x, y)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>