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

时间:2018-04-05 10:19:50

标签: python django dictionary

我试图在django 2.0中实现below answer

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())

但是我收到了这个错误:

unsupported operand type(s) for +: 'dict_items' and 'odict_items'

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

2 个答案:

答案 0 :(得分:4)

尝试相互添加时,不能将+与字典一起使用(与支持+运算符的列表不同)。

改为使用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)])

可替换地:

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}

答案 1 :(得分:0)

您可以使用OR operator|merge the 2 dictionaries in python 3

metadata = {
    "pk": smart_text(obj._get_pk_val(), strings_only=True),
    "model": smart_text(obj._meta),
    "title": smart_text(obj.training_type.name)
}
return dict(metadata.items() | self._current.items())