how to combine 2 dictionaries in python code example

Example 1: join two dictionaries python

z = {**x, **y}

Example 2: python merge two dictionaries in a single expression

z = {**x, **y}  #python 3.5 and above

z = x | y    #python 3.9+ ONLY

def merge_two_dicts(x, y): # python 3.4 or lower
      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

Example 3: merge two dict python 3

z = {**x, **y}

Example 4: python merge dictionaries

# Python >= 3.5:
def merge_dictionaries(a, b):
   return {**a, **b}
  
# else:
def merge_dictionaries(a, b):
    c = a.copy()   # make a copy of a 
    c.update(b)    # modify keys and values of a with the b ones
    return c

a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b)) 		# {'y': 3, 'x': 1, 'z': 4}