2011-04-01 75 views
0


我有以下模块root_file.py。这个文件包含一些块。字典从模块读取

Name = { 
'1':'a' 
'2':'b' 
'3':'c' 
} 

在其他文件中,我使用

f1= __import__('root_file') 

现在的要求是,我要读a

id=1 
app=Name 
print f1[app][id] 

,但得到的错误阅读在使用像 变量运行值a,b,c

TypeError: unsubscriptable object 

回答

2

如何

import root_file as f1 

id = 1 
app = 'Name' 
print getattr(f1, app)[id] # or f1.Name[id] 
+0

感谢您的工作,我可以告诉我,有什么区别之间导入root_file为f1和f1 = __导入__('root_file') – 2011-04-01 14:27:41

+0

前看起来更清洁,不是吗。 – Shekhar 2011-04-02 05:45:50

+0

多数民众赞成可以但任何技术差异 – 2011-04-04 09:10:10

1

呃,好吧,如果我明白你正在尝试做的:

在root_file.py

Name = { 
'1':'a', #note the commas here! 
'2':'b', #and here 
'3':'c', #the last one is optional 
} 

那么,在其他的文件:

import root_file as mymodule 
mydict = getattr(mymodule, "Name") 
# "Name" could be very well be stored in a variable 
# now mydict eqauls Name from root_file 
# and you can access its properties, e.g. 
mydict['2'] == 'b' # is a True statement 
+0

是的,只是试图访问值 – 2011-04-01 14:39:29