Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Why can't I unpack a tuple into a dictionary?

Why doesn't this work?:

d["a"], d["b"] = *("foo","bar")

Is there a better way to achieve what I'm trying to achieve?

like image 680
jsj Avatar asked Feb 13 '13 13:02

jsj


People also ask

How do you convert a tuple to a dictionary in Python?

In Python, use the dict() function to convert a tuple to a dictionary. A dictionary object can be created with the dict() function. The dictionary is returned by the dict() method, which takes a tuple of tuples as an argument.

Can you unpack a tuple in Python?

Python tuples are immutable means that they can not be modified in whole program. Packing and Unpacking a Tuple: In Python, there is a very powerful tuple assignment feature that assigns the right-hand side of values into the left-hand side. In another way, it is called unpacking of a tuple of values into a variable.

Can you add a tuple to a dictionary Python?

Practical Data Science using Python When it is required to add a dictionary to a tuple, the 'list' method, the 'append', and the 'tuple' method can be used. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

Is unpacking possible in a tuple?

Unpacking a Tuple Note: The number of variables must match the number of values in the tuple, if not, you must use an asterisk to collect the remaining values as a list.


2 Answers

It would work if you define a dictionary d before hand, and remove the * from there:

>>> d = {}
>>> d["a"], d["b"] = ("foo","bar")

In fact, you don't need those parenthesis on the RHS, so this will also work:

>>> d['a'], d['b'] = 'foo', 'bar'
like image 182
Rohit Jain Avatar answered Oct 23 '22 00:10

Rohit Jain


Others have showed how you can unpack into a dict. However, in answer to your question "is there a better way", I would argue that:

d.update(a='foo',b='bar')

much easier to parse. Admitedtly, this doesn't work if you have a and b which are variables, but then you could use:

d.update({a:'foo',b:'bar'})

and I think I still prefer that version for the following reasons:

  • It scales up to multiple (>2) values nicer as it can be broken onto multiple lines more cleanly
  • It makes it immediately clear which key is associated with which value

And if you start off with a 2-tuple of values, rather than it being static as you show, you could even use zip:

d.update( zip(("a","b"),("foo","bar")) )

which is admittedly not as nice as the other two options ...

... And we've just covered all 3 ways you can use dict.update :).

like image 31
mgilson Avatar answered Oct 23 '22 00:10

mgilson