Simpler way to create dictionary of separate variables?

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

    I find that if you already have a specific list of values, that the way described by @S. Lotts is the best; however, the way described below works well to get all variables and Classes added throughout the code WITHOUT the need to provide variable name though you can specify them if you want. Code can be extend to exclude Classes.

    import types
    import math  # mainly showing that you could import what you will before d
    
    # Everything after this counts
    d = dict(globals())
    
    def kv_test(k,v):
        return (k not in d and 
                k not in ['d','args'] and
                type(v) is not types.FunctionType)
    
    def magic_print(*args):
        if len(args) == 0: 
            return {k:v for k,v in globals().iteritems() if kv_test(k,v)}
        else:
            return {k:v for k,v in magic_print().iteritems() if k in args}
    
    if __name__ == '__main__':
        foo = 1
        bar = 2
        baz = 3
        print magic_print()
        print magic_print('foo')
        print magic_print('foo','bar')
    

    Output:

    {'baz': 3, 'foo': 1, 'bar': 2}
    {'foo': 1}
    {'foo': 1, 'bar': 2}
    

提交回复
热议问题