I would like to do something like this
def f():
return { 'a' : 1, 'b' : 2, 'c' : 3 }
{ a, b } = f() # or { 'a', 'b' } = f() ?
I.e. so that a gets assigned 1, b gets 2, and c is undefined
This is similar to this
def f()
return( 1,2 )
a,b = f()
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.
Assign Values to Multiple Variables in One Line Given above is the mechanism for assigning just variables in Python but it is possible to assign multiple variables at the same time. Python assigns values from right to left.
In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.
With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.
It wouldn't make any sense for unpacking to depend on the variable names. The closest you can get is:
a, b = [f()[k] for k in ('a', 'b')]
This, of course, evaluates f()
twice.
You could write a function:
def unpack(d, *keys)
return tuple(d[k] for k in keys)
Then do:
a, b = unpack(f(), 'a', 'b')
This is really all overkill though. Something simple would be better:
result = f()
a, b = result['a'], result['b']
Hmm. Kind of odd since a dictionary is not ordered, so the value unpacking depends on the variable names. But, it's possible, if ugly:
>>> locals().update(f())
>>> a
1
Don't try this at home! It's a maintainability nightmare. But kinda cool too :-)
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