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 1641
逝去的感伤
逝去的感伤 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:45

    You can use list or generator comprehensions to build a list of key, value tuples used to directly instantiate a dict. The best way is below:

    dict((name, eval(name)) for name in list_of_variable_names)
    

    In addition, if you know, for example, that the variables exist in the local symbol table you can save yourself from the dangerous eval by looking the variable directly from locals:

    dict((name, locals()[name]) for name in list_of_variable_names)
    

    After your final update, I think the answer below is really what you want. If you're just using this for string expansion with strings that you control, just pass locals() directly to the string expansion and it will cherry-pick out the desired values

    If, however, these strings could ever come from an outside source (e.g. translation files), than it's a good idea to filter locals()

提交回复
热议问题