Assign contents of Python dict to multiple variables at once?

前端 未结 5 2202
滥情空心
滥情空心 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:21

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

提交回复
热议问题