python - 将字典键转换为具有字典值的变量的最佳方法是什么?
问题描述
我可以在没有globals
orlocals
的情况下将字典转换为变量值对exec
,例如:
count = { 'one':'first', 'two':'second'}
for key in count.keys():
key = count.get(key)
然后我需要:
print(one)
'first'
但它没有发生。我可以这样做吗?如何?
解决方案
如果您愿意创建一个对象,那么您可以像使用变量一样使用getattr
andsetattr
添加和获取其属性。
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
推荐阅读
- ios - 单行 UICollectionView 动态高度
- go - 为什么不 byte.NewBuffer 接受全身请求?
- javascript - Node.js 环境变量未定义
- blazor-server-side - 如何配置 Blazor Web 服务器以侦听 IP 地址?
- angular - 验证 Angular 中的重复输入字段
- javascript - Vue - 嵌套组件不会更新其数据并重新渲染
- python - 如何将输出保存在嵌套字典中?
- apache-spark - Pyspark:如何改善空间交叉点?
- java - Point2D 等于阈值内
- c# - 将数组作为参数传递时更改数组的初始值