python - 判断是否在字典里用in还是用has_key()
巴扎黑
巴扎黑 2017-04-17 11:08:18
0
3
995

这两个都是一样的结果呢

z = {'a': 1, 'b': 2, 'c':3}
'a' in z
z.has_key('a')
巴扎黑
巴扎黑

reply all(3)
洪涛

Official documentation recommends using key in dict syntax because it is shorter and easier to understand. has_key is an old legacy API, left behind to support code before 2.2. This function has been removed in Python3.

PHPzhong

The information above is detailed enough, so I’ll just post some code:

#src/Python-2.6.8/Objects/dictobject.c

static PyObject *
dict_has_key(register PyDictObject *mp, PyObject *key)
{
    if (PyErr_WarnPy3k("dict.has_key() not supported in 3.x; "
                       "use the in operator", 1) < 0) 
        return NULL;
    return dict_contains(mp, key);
}
小葫芦

is the same, in has a more pythonic feel, has_key has been removed in python3: http://docs.python.org/3.1/whatsnew/3...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template