我试图在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'
如何合并普通字典和有序字典?
答案 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())