2017-05-23 42 views
0

奇怪的時間讓這個工作;記錄遞歸詞典

我有一個包含多臺機器信息的字典。根據參數選擇機器。

我想將選定的信息寫入日誌。但是我的遞歸嘗試似乎並沒有讓我走到需要去的地方。我得到鑰匙但價值失敗。

這是字典

CSTU_CFG = {'A07': {    
     'password': 'CastAIP',       # default cast password(too lazy to use LDAP) 
     'host':'JSIPVWCASTD01', 
     'port':'2280',         # Ports are assumed to be 2280 but can be any 
     'location': 'C:Users/WDI/Documents/CSTU/DMPRST', # use os.path to convert 
     'gzips': 'GZIPS',        # location for zip files (Backup) 
     'schematype':{'local', 'central', 'mngt'}, 
     'logintv': 30, 
     'version': '0.9' 
     }, 
     'A01': { 
     'machine': 'A01', 
     'password': 'CastAIP',       # default cast password(too lazy to use LDAP) 
     'host':'JSIPVWCASTD01', 
     'port':'2280',         # Ports are assumed to be 2280 but can be any 
     'location': 'C:Users/WDI/Documents/CSTU/DMPRST', # use os.path to convert 
     'gzips': 'GZIPS',        # location for zip files (Backup) 
     'schematype':{'local', 'central', 'mngt'}, 
     'logintv': 30, 
     'version': '0.9' 
     }, 
     'A02': { 
     'machine': 'A02', 
     'password': 'CastAIP',       # default cast password(too lazy to use LDAP) 
     'host':'JSIPVWCASTD01', 
     'port':'2280',         # Ports are assumed to be 2280 but can be any 
     'location': 'C:Users/WDI/Documents/CSTU/DMPRST', # use os.path to convert 
     'gzips': 'GZIPS',        # location for zip files (Backup) 
     'schematype':{'local', 'central', 'mngt'}, 
     'logintv': 30, 
     'version': '0.9' 
     } 
    } 

logname = 'CSTU_'+timestr+'_'+ schemaname + '.CLOG'   
logging.basicConfig(filename=logname,filemode='a',format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S',level=logging.DEBUG) 
logging.debug("Starting CSTU_DUMP") 

# print the CSTU_CFG file into the log 

for key,value in CSTU_CFG: 
    logging.debug(key + " => " + value)  

我顯然沒有得到上記錄點。我已經嘗試了一些建議的修復方法,但是我什麼也沒得到,或者出現了各種錯誤。我可以硬編碼它,但那不是意圖。 謝謝

回答

0

可以遍歷字典來獲得鍵和鍵值:

for k, v in CSTU_CFG.iteritems(): 
    logging.debug(k, v) 
0

要迭代字典項目,您需要首先訪問項目,而不是直接迭代字典。

您需要更改您的代碼(for key,value in CSTU_CFG),如下所示。

對於Python 2.x的:

for key, value in CSTU_CFG.iteritems(): 
    logging.debug(key + " => " + str(value)) 

對於Python 3.x的:

for key, value in CSTU_CFG.items(): 
    logging.debug(key + " => " + str(value)) 

順便說一句,你說你得到的錯誤。這可能有助於在下次問題中包含確切的錯誤跟蹤。

+0

謝謝你 - 這是有道理的和完美。日誌記錄需要一個字符串,所以我需要將鍵和值重新設置爲一個字符串,但效果很好。謝謝 ! (下次我會列出各種錯誤,再次感謝你) – WDickens

+0

不客氣。請考慮將答案標記爲已接受和/或贊成。 –

+0

尋找如何,現在。謝謝 – WDickens