2014-10-16 64 views
0

我在我的代码中定义了一个名为cfg的字典。试图用另一个“字典”更新字典

cfg = { 'debug': 1, 'verbose': 1, 'cfgfile': 'my.cfg' } 

使用ConfigParser我分析可用于覆盖在上面cfg定义的硬编码值和如下合并它们的配置文件:

config = SafeConfigParser() 
config.read(cfg['cfgfile']) 
cfg.update(dict(config.items('Main'))) 

上述所有工作正常。

我现在调用一个函数,它使用optparse来解析命令行参数。

def parseOptions(): 
    parser = OptionParser() 
    parser.add_option("-d", "", dest="debug",  action="store_true",    default=False, help="enable additional debugging output") 
    parser.add_option("-v", "", dest="verbose",  action="store_true",    default=False, help="enable verbose console output") 

    (options, args) = parser.parse_args() 

    return options 

早在main()options似乎是在目测时的字典:

options = parseOptions() 
print options 

{'debug': False, 'verbose': False} 

当我尝试更新我的cfg字典,我得到这个错误:

cfg.update(dict(options)) 

输出:

Traceback (most recent call last): 
    File "./myscript.py", line 176, in <module> 
    cfg.update(dict(options)) 
TypeError: iteration over non-sequence 

类型的选项是价值观的一个实例:

print "type(options)=%s instanceof=%s\n" % (type(options), options.__class__.__name__) 

type(options)=<type 'instance'> instanceof=Values 

我如何更新我的cfg字典,在options值是多少?

回答

2

尝试使用vars()

options = parseOptions() 
option_dict = vars(options) 
cfg.update(option_dict) 
+0

真棒,就像一个魅力! – BenH 2014-10-16 13:36:03