Reputation: 9421
Why doesn't this work?:
d["a"], d["b"] = *("foo","bar")
Is there a better way to achieve what I'm trying to achieve?
Upvotes: 10
Views: 5481
Reputation: 213351
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'
Upvotes: 19
Reputation: 310089
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
:).
Upvotes: 9
Reputation: 18446
It's just a typo (the *
). This works (tested in Python 2.7.3):
d = dict()
d["a"], d["b"] = ("foo", "bar")
Upvotes: 0