Simpler way to create dictionary of separate variables?

前端 未结 27 1897
名媛妹妹
名媛妹妹 2020-11-22 02:42

I would like to be able to get the name of a variable as a string but I don\'t know if Python has that much introspection capabilities. Something like:

>&         


        
27条回答
  •  情歌与酒
    2020-11-22 03:31

    Maybe I'm overthinking this but..

    str_l = next((k for k,v in locals().items() if id(l) == id(v)))
    
    
    >>> bar = True
    >>> foo = False
    >>> my_dict=dict(bar=bar, foo=foo)
    >>> next((k for k,v in locals().items() if id(bar) == id(v)))
    'bar'
    >>> next((k for k,v in locals().items() if id(foo) == id(v)))
    'foo'
    >>> next((k for k,v in locals().items() if id(my_dict) == id(v)))
    'my_dict'
    

提交回复
热议问题