给定Python中的变量名列表

给定Python中的变量名列表

本文介绍了给定Python中的变量名列表,如何创建一个以变量名作为键(指向变量值)的字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量名列表,如下所示:

I have a list of variable names, like this:

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

(我最初问我如何转换变量列表.请参见下面的Greg Hewgill的答案.)

(I originally asked how I convert a list of variables. See Greg Hewgill's answer below.)

如何将其转换为字典,其中键是变量名(作为字符串),值是变量的值?

How do I convert this to a dictionary where the keys are the variable names (as strings) and the values are the values of the variables?

{'foo': foo, 'bar': bar, 'baz': baz}

现在我在重新提问,我想到了:

Now that I'm re-asking the question, I came up with:

d = {}
for name in list_of_variable_names:
    d[name] = eval(name)

可以改进吗?

更新,回答有关为什么要这样做的问题(在评论中):

Update, responding to the question (in a comment) of why I'd want to do this:

我经常发现自己使用%运算符对要插入的名称和值的字典进行字符串化.通常,字符串中的名称只是局部变量的名称.因此(使用下面的答案),我可以做这样的事情:

I often find myself using the % operator to strings with a dictionary of names and values to interpolate. Often the names in the string is just the names of local variables. So (with the answer below) I can do something like this:

message = '''Name: %(name)s
ZIP: %(zip)s

Dear %(name)s,
...''' % dict((x, locals()[x]) for x in ['name', 'zip'])

推荐答案

忘记过滤locals()!您提供给格式字符串的字典允许包含未使用的键:

Forget filtering locals()! The dictionary you give to the formatting string is allowed to contain unused keys:

>>> name = 'foo'
>>> zip = 123
>>> unused = 'whoops!'
>>> locals()
{'name': 'foo', 'zip': 123, ... 'unused': 'whoops!', ...}
>>> '%(name)s %(zip)i' % locals()
'foo 123'

使用Python 3.6中的新 f字符串功能 locals()不再是必需的:

With the new f-string feature in Python 3.6, using locals() is no longer necessary:

>>> name = 'foo'
>>> zip = 123
>>> unused = 'whoops!'
>>> f'{zip: >5} {name.upper()}'
'  123 FOO'

这篇关于给定Python中的变量名列表,如何创建一个以变量名作为键(指向变量值)的字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 01:33