Search code examples
pythonpython-3.xdictionarytypeerrorpython-3.8

TypeError when merging dictionaries: unsupported operand type(s) for |: 'dict' and 'dict'


I wanted to join two dictionaries using | operator and I got the following error:

TypeError: unsupported operand type(s) for |: 'dict' and 'dict'

The MWE code is the following:

d1 = {'k': 1, 'l': 2, 'm':4}
d2 = {'g': 3, 'm': 7}

e = d1 | d2

Solution

  • The merge (|) and update (|=) operators for dictionaries were introduced in Python 3.9 so they do not work in older versions. You have an option to either update your Python interpreter to Python 3.9 or use one of the alternatives:

    # option 1:
    e = d1.copy()
    e.update(d2)
    
    # option 2:
    e = {**d1, **d2}
    

    However, should you want to update to Python 3.9 you can save some memory updating dictionary d1 directly instead of creating another dictionary using in-place merge operation:

    d1 |= d2
    

    Which is equivalent of the following in the older versions of Python:

    d1.update(d2)