9

Why doesn't this work?:

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

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

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
jsj
  • 9,019
  • 17
  • 58
  • 103

3 Answers3

18

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'
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
9

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

mgilson
  • 300,191
  • 65
  • 633
  • 696
0

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

d = dict()
d["a"], d["b"] = ("foo", "bar")
Carsten
  • 17,991
  • 4
  • 48
  • 53
  • 1
    It's not a typo. He used an unpacking operator which is used with lists and args. There is no need to use this operator when working with tuples. :) – Marek Marczak Sep 26 '18 at 10:25