Simpler way to create dictionary of separate variables?

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

    This is a hack. It will not work on all Python implementations distributions (in particular, those that do not have traceback.extract_stack.)

    import traceback
    
    def make_dict(*expr):
        (filename,line_number,function_name,text)=traceback.extract_stack()[-2]
        begin=text.find('make_dict(')+len('make_dict(')
        end=text.find(')',begin)
        text=[name.strip() for name in text[begin:end].split(',')]
        return dict(zip(text,expr))
    
    bar=True
    foo=False
    print(make_dict(bar,foo))
    # {'foo': False, 'bar': True}
    

    Note that this hack is fragile:

    make_dict(bar,
              foo)
    

    (calling make_dict on 2 lines) will not work.

    Instead of trying to generate the dict out of the values foo and bar, it would be much more Pythonic to generate the dict out of the string variable names 'foo' and 'bar':

    dict([(name,locals()[name]) for name in ('foo','bar')])
    

提交回复
热议问题