【发布时间】:2010-12-10 23:36:35
【问题描述】:
我正在从 CSV 导入数据并获取大致格式的数据
{ 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 }
字段的名称是动态的。 (嗯,它们是动态的,因为可能不止 Field1 和 Field2,但我知道 Field1 和 Field2 总是会在那里。
我希望能够将此字典传递给我的类allMyFields,以便我可以将上述数据作为属性访问。
class allMyFields:
# I think I need to include these to allow hinting in Komodo. I think.
self.Field1 = None
self.Field2 = None
def __init__(self,dictionary):
for k,v in dictionary.items():
self.k = v
#of course, this doesn't work. I've ended up doing this instead
#self.data[k] = v
#but it's not the way I want to access the data.
q = { 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 }
instance = allMyFields(q)
# Ideally I could do this.
print q.Field1
有什么建议吗?至于为什么——我希望能够利用代码提示,并将数据导入到名为data 的字典中,就像我一直在做的那样,我没有任何能力。
(由于变量名直到运行时才被解析,我仍然不得不向 Komodo 扔骨头 - 我认为 self.Field1 = None 应该足够了。)
那么 - 我该如何做我想做的事?还是我在咆哮一棵设计不佳的非 python 树?
【问题讨论】:
-
科莫多编辑提示不需要类属性。它可以读取
__init__方法体来查找self.变量。更根本的是,您为什么不为此使用简单的csv.DictReader并从每一行创建字典? -
SLott - 我使用 re.sub() 手动修改标题并添加“假”标题。这不是一个很好的理由,但是在 DictReader 之后重命名密钥要昂贵得多。