Assign Python dict contents 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() ?

those. so a gets 1, b gets 2, and c gets undefined

It looks like this

def f()
    return( 1,2 )

a,b = f()
+5
source share
4 answers

For unpacking, it made no sense to depend on variable names. The closest you can get is:

a, b = [f()[k] for k in ('a', 'b')]

This, of course, is rated twice f().


You can write a function:

def unpack(d, *keys)
    return tuple(d[k] for k in keys)

Then do:

a, b = unpack(f(), 'a', 'b')

It really is all crowded. Something simple would be better:

result = f()
a, b = result['a'], result['b']
+8
source

Consider creating fa namedtuplethen you can just use f.a, f.bdirectly

+5
source

. , , . , , :

>>> locals().update(f())
>>> a
1

! . : -)

+3

( ) :

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

Remember that attributes only matter after f () is called or manually assigned.

I (rarely) use function attributes as padding for class C variables static, for example:

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

0
source

All Articles