So, I have a code that contains a dictionary, and I'm doing some checking in a dictionary. The verification rule basically consists in the fact that the dictionary can contain either the "to" key or the "from" key. Whatever it is, I need to return a value so that I can check the length for the length of another key in the dictionary.
I really found a better way to solve the immediate problem, but while working on it, I came across curious behavior in Python 2.7.1, which implies that dict.get () does not work as I thought, so I'm looking for some clarification before I start diving into the C-version of the dictionary, which I’m not in a hurry to do :)
The short summary version is that if you pass the default value to .get (), Python tries to evaluate that default value, even if the first argument is a valid key in the dictionary.
Here is an example:
>>> toparm = 'to'
>>> toarrparm = 'to[]'
>>> d = {toparm: 'foo'}
>>> d.get(toarrparm, [d[toparm]])
['foo']
>>> d = {toarrparm: ['foo', 'bar']}
>>> d.get(toarrparm, [d[toparm]])
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 'to'
>>> d
{'to[]': ['foo', 'bar']}
>>> toarrparm
'to[]'
>>> sys.version
'2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) \n[GCC 4.2.1 (Apple Inc. build 5664)]'
>>> d['to[]'] = ['foo', 'bar', 'baz']
>>> d
{'to[]': ['foo', 'bar', 'baz']}
>>> d.get(toarrparm)
['foo', 'bar', 'baz']
>>> d.get(toarrparm, [d[toparm]])
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 'to'
>>> d
{'to[]': ['foo', 'bar', 'baz']}
>>> d['to'] = 'foo'
>>> d.get(toarrparm, [d[toparm]])
['foo', 'bar', 'baz']
>>>
If this behavior is old news, can someone explain why this would be? Should I just always ask about what, in my opinion, no? What if I really don't know which one will be there? Just come back to try / exclude? Did I miss something else?