4 ms·
You really wouldn't like Python or even stricter languages such as Scala or java, then. In Python, an attempt to access a nonexistent dictionary key will throw
by code_duck 15y ago
You really wouldn't like Python or even stricter languages such as Scala or java, then. In Python, an attempt to access a nonexistent dictionary key will throw an exception which halts execution if not caught. (similar to calling a nonexistent method or function in PHP, but since PHP doesn't have a well-thought out exception system/std. lib as Python does, you can't catch anything in that situation in PHP).
- cheald 15y agoIn Python, if you're expecting a potentially missing key, you can just use dict.get('key') rather than dict['key']. The equivalent in PHP would be something like: $val = array_key_exists('key', $dict) ? $dict['key'] : NULL; Being able to say "I expect a potentially nil value (and am okay with that)" via get() rather than array index is both semantically useful, and far more beautiful than the PHP equivalent.
- Luyt 15y agoThe more so because get() can also take a default value to return if the key is not present in the dict ;-)
- code_duck 15y agoSure, or you can catch a KeyError and do something else entirely. I'm aware of all this, just pointing out some differences to the person to whom I replied. Python's dict.get is a bit like the getOrElse found in Scala. It's quite handy and can be seen as advanced conceptually. I actually added some code like that to a recent post about PHP here: http://news.ycombinator.com/item?id=2771304 http://news.ycombinator.com/item?id=2771304