search

Home  >  Q&A  >  body text

python - 判断是否在字典里用in还是用has_key()

这两个都是一样的结果呢

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

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 11:10:18

    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.

    reply
    0
  • PHPz

    PHPz2017-04-17 11:10:18

    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);
    }

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 11:10:18

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

    reply
    0
  • Cancelreply