首页 > 解决方案 > 将字典键转换为具有字典值的变量的最佳方法是什么?

问题描述

我可以在没有globalsorlocals的情况下将字典转换为变量值对exec,例如:

count = { 'one':'first', 'two':'second'}
for key in count.keys():
    key = count.get(key)

然后我需要:

print(one)
'first'

但它没有发生。我可以这样做吗?如何?

标签: pythondictionaryvariables

解决方案


如果您愿意创建一个对象,那么您可以像使用变量一样使用getattrandsetattr添加和获取其属性。

class Values(object):
    pass

obj = Values()

count = {'one':'first', 'two':'second'}

for key, value in count.items():
    setattr(obj, key, value)

print(getattr(obj, 'one'))
print(getattr(obj, 'two'))

# first
# second

推荐阅读