Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign contents of Python dict to multiple variables at once?

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()
like image 911
joelhoro Avatar asked Jun 23 '12 22:06

joelhoro


People also ask

How do you assign a value to multiple variables in Python?

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.

Can we assign multiple values to multiple variables at a time in Python?

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.

Can dictionary have multiple values Python?

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.

Should I use dict () or {}?

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.


2 Answers

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']
like image 154
Eric Avatar answered Sep 19 '22 14:09

Eric


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

like image 28
Cameron Avatar answered Sep 18 '22 14:09

Cameron