Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 399
Blade McCool Avatar asked Nov 28 '12 23:11

Blade McCool


People also ask

How to get a tuple as a key from a Python dictionary?

In Python the dict () method takes a list of tuples as an argument and each tuple store key-value pair element and it returns into a dictionary. Here is the Output of the following given code Let us see how to get a tuple as a key from a Python dictionary.

How to sort a dictionary by tuples in Python?

In Python to sort a dictionary by tuples, we can use the combination of dict (), sorted (), and lambda () function. In this example dict () method is used to rearrange the elements and reassigns the dictionary by order.

Can a tuple change in Python?

That means, a tuple can’t change. Use a tuple, for example, to store information about a person: their name, age, and location. Here’s how you’d write a function that returns a tuple.

What is the difference between tuple and parentheses in Python?

The parentheses are optional, however, it is a good practice to use them. A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.).


2 Answers

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'>
like image 192
Andrew Clark Avatar answered Sep 28 '22 09:09

Andrew Clark


There is a trailing comma at your box assignment

like image 21
Jesse the Game Avatar answered Sep 28 '22 09:09

Jesse the Game