TypeError: unsupported operand type(s) for +: ‘dict_items’ and ‘dict_items’ [duplicate]

As of Python 3.9 (PEP 584 in particular), dicts gains union (|) and update (|=) operations just like sets, so that becomes the “one true way” to achieve what you are looking for.

d1 | d2

That PEP lists the other options available in earlier Python versions, which all have their downsides. If you are up to PEP 448 (Python 3.5), I would recommend using:

{**d1, **d2}

This is unpacking both dictionaries into a new one, resulting in a union.

One problem is the behavior you want is ambiguous – dictionaries can’t have duplicate keys, so it is unclear what you want to happen if both contain the same key. The spec is explicit about what should happen when using this method:

In dictionaries, later values will always override earlier ones

If you want the reverse behaviour, you can simply swap the order of the dictionaries in the literal.

Your approach doesn’t work because dictionary views are set-like, so they don’t have addition implemented.

What you probably want is the union: d1.items() | d2.items(), which will give you a set of tuples of (key, value). If you then pass it to dict() and there are duplicates, the “last” value will be the one used, however sets (unlike the views themselves) are unordered, so there is no guarantee about which item will end up “first” in the combined set, meaning that which one “wins” will be arbitrary.

So, in short, as long as order/duplicate selection isn’t important:

dict(d1.items() | d2.items())

In Python 2, dict.items() simply returns a list, where your approach will work.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)