Python safe dictionary key access

This question already has an answer here:

  • Check if a given key already exists in a dictionary 18 answers
  • Access dict key and return None if doesn't exist 6 answers

  • You missed the canonical method, dict.get() :

    color_1 = data.get('color')
    

    It'll return None if the key is missing. You can set a different default as a second argument:

    color_2 = dict.get('color', 'red')
    

    Check out dict.get() . You can supply a value to return if the key is not found in the dictionary, otherwise it will return None .

    >>> data = {'color': 'yellow'}
    >>> data.get('color')
    'yellow'
    >>> data.get('name') is None
    True
    >>> data.get('name', 'nothing')
    'nothing'
    
    链接地址: http://www.djcxy.com/p/28886.html

    上一篇: Python字典故障安全

    下一篇: Python安全字典键访问