質問

Why doesn't this work?:

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

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

役に立ちましたか?

解決

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:

  • 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 :).

It's just a typo (the *). This works (tested in Python 2.7.3):

d = dict()
d["a"], d["b"] = ("foo", "bar")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top