2

update() メソッドを避けたいのですが、「+」オペランドを使用して 2 つの辞書を 3 つ目の辞書にマージできることを読みましたが、私のシェルでは次のようになります。

>>> {'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'

どうすればこれを機能させることができますか?

4

2 に答える 2

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

また

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

Python 3 では、Python 2 のような like をitems返しませんが、 dict viewを返します。を使用する場合は、それらをsに変換する必要があります。list+list

updateありまたはなしで使用する方が良いですcopy

# doesn't change the original dicts
new_dict = {'a':1, 'b':2}.copy()
new_dict.update({'x':98, 'y':99})
于 2011-08-17T17:33:27.060 に答える