Destructuring-bind dictionary contents

前端 未结 12 1086
無奈伤痛
無奈伤痛 2020-12-02 15:24

I am trying to \'destructure\' a dictionary and associate values with variables names after its keys. Something like

params = {\'a\':1,\'b\':2}
a,b = params.         


        
12条回答
  •  自闭症患者
    2020-12-02 15:42

    Python is only able to "destructure" sequences, not dictionaries. So, to write what you want, you will have to map the needed entries to a proper sequence. As of myself, the closest match I could find is the (not very sexy):

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

    This works with generators too:

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

    Here is a full example:

    >>> d = dict(a=1,b=2,c=3)
    >>> d
    {'a': 1, 'c': 3, 'b': 2}
    >>> a, b = [d[k] for k in ('a','b')]
    >>> a
    1
    >>> b
    2
    >>> a, b = (d[k] for k in ('a','b'))
    >>> a
    1
    >>> b
    2
    

提交回复
热议问题