Arc Forumnew | comments | leaders | submitlogin
4 points by EliAndrewC 6137 days ago | link | parent

This is a little nit-picky, but the canonical way of checking for the existence of a key in a Python dictionary is

    if "username" in some_dict:
        ...


1 point by bayareaguy 6137 days ago | link

Even since this started to work, I still prefer some_dict.has_key("username") because then if an ordinary string accidently found its way into some_dict I'd get a runtime error instead of a silent logic bug.

-----

1 point by ivankirigin 6137 days ago | link

Yah, and I usually just try to grab it, with a default value. Both these options are fine:

  some_dict.get("username", "default")
or

  try:
    u = some_dict["username"]
  except KeyError:
    # long error case code if needed

-----

1 point by akkartik 6137 days ago | link

Gahd, I can never remember that.

-----