Python字典类,'KeyError'

时间:2012-08-07 23:38:21

标签: python dictionary

我有以下类用于存储其他对象访问的设置:

#!/usr/bin/env python                                                           

class Settings:                                                                    
    """Singleton settings class"""                                              

    settings = {                                                                   
                   'SectionA': {'a': 1, 'b': 2, 'c': 3},                           
                   'SectionB': {'d': 4, 'e': 5, 'f': 6}                            
               }                                                                   

    def __getitem__(self, key): return self.settings[key]                          
    def __setitem__(self, key, item): self.settings[key] = item                    
    def keys(self): return self.settings.keys()                                    

s = Settings()                                                                     
print s.keys()                                                                     
print s['SectionA']                                                                
print s['SectionB']                                                                

for key in s: print s[key]    

我无法理解为什么它会产生以下输出或如何绕过它,任何帮助都非常感激:

foo@bar:~$ python Settings.py
['SectionB', 'SectionA']
{'a': 1, 'c': 3, 'b': 2}
{'e': 5, 'd': 4, 'f': 6}
Traceback (most recent call last):
  File "Settings.py", line 20, in <module>
    for key in s: print s
  File "Settings.py", line 11, in __getitem__
    def __getitem__(self, key): return self.settings[key]
KeyError: 0
foo@bar:~$

2 个答案:

答案 0 :(得分:4)

那是因为当你在Settings类上进行迭代时,它显然会尝试通过索引迭代它,就像列表一样。第一个索引是0,它给出了一个KeyError,因为它不在你的dict中。您必须定义特殊方法来覆盖for key in s语法以迭代密钥。

def __iter__(self): return iter(self.settings)

编辑:另一件事是您正在使用已弃用的旧样式类。您应该将其更改为Settings(object)

答案 1 :(得分:1)

这有效:

class Settings(dict):                                                                    
    """Singleton settings class"""                                              

    settings = {                                                                   
                   'SectionA': {'a': 1, 'b': 2, 'c': 3},                           
                   'SectionB': {'d': 4, 'e': 5, 'f': 6}                            
               }                                                                   

    def __getitem__(self, key): return self.settings[key]                          
    def __setitem__(self, key, item): self.settings[key] = item                    
    def keys(self): return self.settings.keys()                                    

s = Settings()                                                                     

for key in s.keys(): 
    print key 
    print s[key]

打印:

SectionB
{'e': 5, 'd': 4, 'f': 6}
SectionA
{'a': 1, 'c': 3, 'b': 2}

修改

看看,没有{}.keys()

class Settings(dict):                                                                    
    """Singleton settings class"""                                              

    settings = {                                                                   
                   'SectionA': {'a': 1, 'b': 2, 'c': 3},                           
                   'SectionB': {'d': 4, 'e': 5, 'f': 6}                            
               }                                                                   

    def __getitem__(self, key): return self.settings[key]                          
    def __setitem__(self, key, item): self.settings[key] = item  
    def __iter__(self): return iter(self.settings.keys())               
    def keys(self): return self.settings.keys()      


s = Settings()                                                                                                                                   

for key in s: 
    print key 
    print s[key]

打印相同的输出......