【问题标题】:dictionary reading from module从模块读取字典
【发布时间】:2011-04-01 14:14:01
【问题描述】:


我有以下模块 root_file.py。此文件包含类似的块数。

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

在我正在使用的其他文件中

f1= __import__('root_file')

现在的要求是我必须在运行时使用变量读取值a,b,c 供阅读a

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

但出现错误

TypeError: unsubscriptable object

【问题讨论】:

    标签: python dictionary module


    【解决方案1】:

    怎么样

    import root_file as f1
    
    id = 1
    app = 'Name'
    print getattr(f1, app)[id] # or f1.Name[id]
    

    【讨论】:

    • 谢谢,这对我有用,你能告诉我 import root_file as f1 和 f1=__import__('root_file') 有什么区别
    • 前者看起来更干净,不是吗。
    • 没关系,但有任何技术差异
    【解决方案2】:

    嗯,好吧,如果我明白你想要做什么:

    在 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
    

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      相关资源
      最近更新 更多