Create dictionary where keys are variable names

前端 未结 4 567
星月不相逢
星月不相逢 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:49

    You can write your own function for create_dict

    def create_dict(*args):
      return dict({i:eval(i) for i in args})
    
    a = "yo"
    b = 7
    print (create_dict("a", "b"))
    

    Which gives {'a': 'yo', 'b': 7} output.
    Here's a simple generator for the same:

    vars = ["a", "b"]
    create_dict = {i:eval(i) for i in args}
    

    or you can use this one-liner lambda function

    create_dict = lambda *args: {i:eval(i) for i in args}
    print (create_dict("a", "b"))
    

    But if you want to pass the variables to the function instead of the variable name as string, then its pretty messy to actually get the name of the variable as a string. But if thats the case then you should probably try using locals(), vars(), globals() as used by Nf4r

提交回复
热议问题