Create dictionary where keys are variable names

前端 未结 4 536
星月不相逢
星月不相逢 2020-12-18 09:22

I quite regularly want to create a dictionary where keys are variable names. For example if I have variables a and b I want to generate: {\"a

4条回答
  •  感情败类
    2020-12-18 09:54

    Have you considered creating a class? A class can be viewed as a wrapper for a dictionary.

    # Generate some variables in the workspace
    a = 9; b = ["hello", "world"]; c = (True, False)
    
    # Define a new class and instantiate
    class NewClass(object): pass
    mydict = NewClass()
    
    # Set attributes of the new class
    mydict.a = a
    mydict.b = b
    mydict.c = c
    
    # Print the dict form of the class
    mydict.__dict__
    {'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}
    

    Or you could use the setattr function if you wanted to pass a list of variable names:

    mydict = NewClass()
    vars = ['a', 'b', 'c']
    for v in vars: 
        setattr(mydict, v, eval(v)) 
    
    mydict.__dict__
    {'a': 9, 'b': ['hello', 'world'], 'c': (True, False)}
    

提交回复
热议问题