Why doesn't this work?:
d["a"], d["b"] = *("foo","bar")
Is there a better way to achieve what I'm trying to achieve?
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.
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.
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).
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.
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'
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:
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
:).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With