Search code examples
pythondictionaryiterable-unpacking

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?


Solution

  • 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'