如何修复此错误:+ 不支持的操作数类型:'dict_items' 和 'odict_items'?

sur*_*190 0 python django dictionary

我正在尝试在 django 2.0 中实现以下答案

def get_dump_object(self, obj):
    metadata = {
        "pk": smart_text(obj._get_pk_val(), strings_only=True),
        "model": smart_text(obj._meta),
    }
    return dict(metadata.items() + self._current.items())
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

unsupported operand type(s) for +: 'dict_items' and 'odict_items'
Run Code Online (Sandbox Code Playgroud)

如何合并普通字典和有序字典?

mu *_*u 無 5

+尝试添加到另一个时,您不能使用字典(与支持+运算符的列表不同)。

使用dict.update来代替:

In [47]: from collections import OrderedDict
    ...: o = OrderedDict([(1,2), (3, 4)])
    ...: d = {5:6, 7:8}
    ...: 

In [48]: o+d
TypeError: unsupported operand type(s) for +: 'collections.OrderedDict' and 'dict'

In [49]: o.update(d)

In [50]: print(o)
OrderedDict([(1, 2), (3, 4), (5, 6), (7, 8)])
Run Code Online (Sandbox Code Playgroud)

或者:

In [52]: from collections import OrderedDict
    ...: o = OrderedDict([(1,2), (3, 4)])
    ...: d = {5:6, 7:8}
    ...: 

In [53]: d.update(o); print(d)
{1: 2, 3: 4, 5: 6, 7: 8}
Run Code Online (Sandbox Code Playgroud)