Assign contents of Python dict to multiple variables at once?

前端 未结 5 2264
滥情空心
滥情空心 2021-02-20 07:41

I would like to do something like this

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

{ a, b } = f()     # or { \'a\', \'b\' } = f() ?
<
5条回答
  •  走了就别回头了
    2021-02-20 08:09

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

提交回复
热议问题