89DEVs

Python: How to concatenate dictionaries?

How to concatenate dictionaries in Python?

To concatenate dictionaries we can choose between different options.

concatenate dictionaries using update() method

To concatenate multiple dictionaries in Python to one dictionary, use the .update() method. # concatenate dictionaries using update() d1={1:2,3:4} d2={5:6,7:8} d3={9:10,11:12} # concatenate d2 and d3 to d1 d1.update(d2) d1.update(d3) # print concatenated dictionary print(d1) The .update() method concatenates d2 and d3 with d1. Then the concatenated dictionary d1 is printed. It includes all element of all 3 dictionaries. {1: 2, 3: 4, 5: 6, 7: 8, 9: 10, 11: 12}

concatenate dictionaries using the ** operator

To concatenate dictionaries in Python, use the ** operator. # concatenate dictionaries using ** operator d1={1:2,3:4} d2={5:6,7:8} d3={9:10,11:12} d = {**d1, **d2, **d3} print(d) All three dictionaries (d1, d2, d3) are concatenated to dictionary d and then printed. {1: 2, 3: 4, 5: 6, 7: 8, 9: 10, 11: 12}

concatenate dictionaries using | operator

In Python 3.9 use the | operator to concatenate dictionaries. # only in python 3.9 - concatenate dictionaries using | operator d1={1:2,3:4} d2={5:6,7:8} d3={9:10,11:12} d = d1 | d2 | d3 print(d) All three dictionaries (d1, d2, d3) are concatenated using the | operator. Then the dictionary d is printed. It contains all elements of the three dictionaries. {1: 2, 3: 4, 5: 6, 7: 8, 9: 10, 11: 12}

                
        

Summary


Click to jump to section