Python check that key is defined in dictionary

This question already has an answer here:

  • Check if a given key already exists in a dictionary 18 answers

  • Use the in operator:

    if b in a:
    

    Demo:

    >>> a = {'foo': 1, 'bar': 2}
    >>> 'foo' in a
    True
    >>> 'spam' in a
    False
    

    You really want to start reading the Python tutorial, the section on dictionaries covers this very subject.


    Its syntax is if key in dict: :

    if "b" in a:
        a["b"] += 1
    else:
        a["b"] = 1
    

    Now you may want to look at collections.defaultdict and (for the above case) collections.Counter .


    a = {'foo': 1, 'bar': 2}
    if a.has_key('foo'):
        a['foo']+=1
    else:
        a['foo']=1
    
    链接地址: http://www.djcxy.com/p/28880.html

    上一篇: 如何检查python中是否存在一个值

    下一篇: Python检查密钥是否在字典中定义