RepugNaNt
I had a disgusting thought just now. I needed to have some Python code check whether a dictionary contains a particular key/value pair. The obvious approach,
if dictionary[key] == value:
isn't sufficient, because I need to not throw an exception if the dictionary doesn't contain any mapping for that key at all.
An obvious way is to use a second clause to handle the latter case, so you end up writing
if key in dictionary and dictionary[key] == value:
But that's unpleasantly verbose, and also undesirable if dictionary
or key
is a complicated expression or one with side effects. So I wondered if we could do better.
Another possibility is to use the get()
method of Python dictionaries, which lets you specify a default return value if the dictionary hasn't got the key in question. So you might say, for instance,
if dictionary.get(key, None) == value:
But in order to be able to do that, you have to be able to think of a default that will guarantee to compare unequal to value
; for instance here, what if the value is None
? If you know something about value
(e.g. its type) then this is probably feasible one way or another, but one can imagine more general situations in which that wouldn't be the case.
I think the right answer, in fact, is to write
if (key, value) in dictionary.viewitems():
where viewitems()
is a standard method which presents the dictionary as if it were a set of ordered pairs. (You could also use dictionary.items()
, which would be semantically equivalent, but much slower due to constructing an explicit list and then iterating along it.)
But before I found the viewitems()
method, I thought a bit harder about the get()
approach. Perhaps, I thought, I could define a class with a comparison method that always returned false, so that an instance of that class would compare unequal to anything, including itself.
And then, as I thought the phrase ‘compare unequal to anything, including itself’, a stray neuron fired in my head. I think this would work pretty reliably:
if dictionary.get(key, float('nan')) == value:
and its only downside is that it is the most disgusting thing ever! :-)