python怎么创建变量,给定Python中的变量名列表,如何创建一个以变量名作为键(指向变量值)的字典?...

博客探讨了如何将变量名列表转换为字典,其中字典的键是变量名,值是变量的值。作者提出了使用`eval()`函数的方法,并分享了一个实际应用场景,即使用格式化字符串操作时,如何方便地从局部变量中提取值。同时,文章提到了Python3.6以后的f-string特性,简化了这个过程。
摘要由CSDN通过智能技术生成

I have a list of variable names, like this:

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

(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)

Can that be improved upon?

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'])

解决方案

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'

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'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值