Key Error 0 on Python dict

Gah! Here’s sampe code that’s hit me a couple of times. So here’s a message for myself, the next time I bang my head on this error: :-)

Try leaving out the __contains__ function and you’ll see the error Key Error: 0, regardless of which key you try to extract from the item = Container(...) object.

class Container(object):

  VALUE_CODE = "valueCode"
  EXPIRY_DATE = "expiryDate"
  VERIFICATION_URL = "verificationUrl"

  item_attributes = "{} {} {}".format(VALUE_CODE, EXPIRY_DATE, VERIFICATION_URL)

  def __init__(self, course_instance_data):
    if isinstance(course_instance_data, Container):
      self._data = course_instance_data._data
    elif isinstance(course_instance_data, dict):
      self._data = dict(course_instance_data)
    else:
      args = type(course_instance_data)
      raise ValueError("Container constructor takes a Container or a dict, got {}".format(args))

    def __contains__(self, item):
      return item in self._data.keys()

    def __getitem__(self, item):
      return self._data[item]


  def _strip_empty_fields(item):
    result = {}
      for key in Container.item_attributes.split():
        if key in item:
          value = item[key]
          if value != "":
            result[key] = value
    return result


if __name__ == '__main__':
  item = Container({"valueCode": "value", "expiryDate": ""})
  print(_strip_empty_fields(item))
This work by Fredrik Wendt is licensed under CC by-sa.