joelhoro
joelhoro

Reputation: 920

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

Upvotes: 16

Views: 14410

Answers (5)

theo olsthoorn
theo olsthoorn

Reputation: 501

mydict = {'aa':2, 'bb':'john', 'cc':34, 'dd':'bye'}

a, b, c, d = [mydict[k] for k in ['aa', 'bb', 'cc', 'dd']]

Upvotes: 1

user648852
user648852

Reputation:

You could use (or abuse) a function attribute to do this:

>>> def f():
...    f.a=1
...    f.b=2
...    return { 'a' : f.a, 'b' : f.b, 'c' : 3 }
... 
>>> f()
{'a': 1, 'c': 3, 'b': 2}
>>> a,b=f.a,f.b
>>> a,b
(1, 2)

Be aware that the attributes only have value after f() is called or manually assigned.

I (rarely) use function attributes as a fill-in for C's static class variables like so:

>>> def f(i):
...    f.static+=i
...    return f.static
>>> f.static=0
>>> f(1)
1
>>> f(3)
4

There are better ways to do this, but just to be complete...

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304473

Consider making f a namedtuple Then you can just use f.a, f.b directly

Upvotes: 6

Eric
Eric

Reputation: 97691

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

Upvotes: 12

Cameron
Cameron

Reputation: 98886

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

Upvotes: 5

Related Questions