2

I'd like to avoid the update() method and I read that is possible to merge two dictionaries together into a third dictionary using the "+" operand, but what happens in my shell is this:

>>> {'a':1, 'b':2}.items() + {'x':98, 'y':99}.items()
Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    {'a':1, 'b':2}.items() + {'x':98, 'y':99}.items()
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
>>> {'a':1, 'b':2} + {'x':98, 'y':99}
Traceback (most recent call last):
  File "<pyshell#85>", line 1, in <module>
    {'a':1, 'b':2} + {'x':98, 'y':99}
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'

How can I get this to work?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
etuardu
  • 5,066
  • 3
  • 46
  • 58
  • 1
    "I read that is possible to merge two dictionaries together into a third dictionary using the "+" operand" - No, it is not. I have no idea where you read it, but it's wrong. – Lennart Regebro Aug 17 '11 at 18:05

2 Answers2

8
dicts = {'a':1, 'b':2}, {'x':98, 'y':99}
new_dict = dict(sum(list(d.items()) for d in dicts, []))

or

new_dict = list({'a':1, 'b':2}.items()) + list({'x':98, 'y':99}.items())

On Python 3, items doesn't return a list like in Python 2, but a dict view. If you want to use +, you need to convert them to lists.

You're better off using update with or without copy:

# doesn't change the original dicts
new_dict = {'a':1, 'b':2}.copy()
new_dict.update({'x':98, 'y':99})
agf
  • 171,228
  • 44
  • 289
  • 238
7

Starting from Python 3.5 the idiom is:

{**dict1, **dict2, ...}

https://www.python.org/dev/peps/pep-0448/

Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120