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

StackOverflow https://stackoverflow.com/questions/13616455

Question

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.

Was it helpful?

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'>

OTHER TIPS

There is a trailing comma at your box assignment

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top