
说明
1、实现字典合并生成新字典的逻辑,对应于 | 操作符。
实现字典就地合并逻辑,对应于 |= 操作符。
2、CPython的实现逻辑与纯Python的实现基本相同,只有引用计数的问题与对象的垃圾回收有关。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | static PyObject *
dict_or(PyObject *self, PyObject *other)
{
if (!PyDict_Check(self) || !PyDict_Check(other)) {
Py_RETURN_NOTIMPLEMENTED;
}
PyObject * new = PyDict_Copy(self);
if ( new == NULL) {
return NULL;
}
if (dict_update_arg( new , other)) {
Py_DECREF( new );
return NULL;
}
return new ;
}
static PyObject *
dict_ior(PyObject *self, PyObject *other)
{
if (dict_update_arg(self, other)) {
return NULL;
}
Py_INCREF(self);
return self;
}
|
以上就是python解释器实现字典合并的方法,希望对大家有所帮助。更多编程基础知识学习:python学习网
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。