Search code examples
pythondictionarygettupleschained

Why does a chained dictionary .get() in python return a tuple when the default provided is not a tuple?


Python 2.6.6 when I call .get on the results of a .get the result is a tuple. This is making no sense to me. Example:

box = {}.get('test1',{}).get('test2','hrmm'),
print type(box)

prints out

<type 'tuple'>

this makes no sense to me. clearly the default in the second get is a simple string. so what gives? thanks for any insight.


Solution

  • You have a trailing comma at the end of the line, so you are getting the result of {}.get('test1',{}).get('test2','hrmm') in a one-element tuple.

    Here is an example of how this works with a simple literal:

    >>> box = 1,
    >>> box
    (1,)
    >>> type(box)
    <type 'tuple'>