Given a list of variable names in Python, how do I a create a dictionary with the variable names as keys (to the variables' values)?

后端 未结 4 1637
逝去的感伤
逝去的感伤 2020-12-17 16:04

I have a list of variable names, like this:

[\'foo\', \'bar\', \'baz\']

(I originally asked how I convert a list of variables. See Greg He

4条回答
  •  一个人的身影
    2020-12-17 16:30

    Not efficient, but without invoking eval:

    dict((k,v) for (k,v) in globals().iteritems() if k in list_of_variable_names)
    

    or

    dict((k,v) for (k,v) in vars().iteritems() if k in list_of_variable_names)
    

    depending on what you want.

提交回复
热议问题