Simpler way to create dictionary of separate variables?

前端 未结 27 2334
名媛妹妹
名媛妹妹 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:24

    Here's the function I created to read the variable names. It's more general and can be used in different applications:

    def get_variable_name(*variable):
        '''gets string of variable name
        inputs
            variable (str)
        returns
            string
        '''
        if len(variable) != 1:
            raise Exception('len of variables inputed must be 1')
        try:
            return [k for k, v in locals().items() if v is variable[0]][0]
        except:
            return [k for k, v in globals().items() if v is variable[0]][0]
    

    To use it in the specified question:

    >>> foo = False
    >>> bar = True
    >>> my_dict = {get_variable_name(foo):foo, 
                   get_variable_name(bar):bar}
    >>> my_dict
    {'bar': True, 'foo': False}
    

提交回复
热议问题