2014-06-26 19 views
-1

我有一個循環,我想建立一個字典。我遇到的代碼部分是鍵和值都是字符串。我不能將IP變量返回字符串轉換爲int,也不是浮點數。可以將兩個字符串參數傳遞給內建函數的python dict()嗎?

這是我的班級的方法我試圖建立詞典。在我感興趣的方法參數'ip'感興趣的IP範圍內有一個循環。

def dictbuild(self,ip): 
    s = pxssh.pxssh() 
    s.force_password = True 
    try: 
     s.login(str(ip), 'root', 'password') 
     s.sendline('hostname') # run a command 
     s.prompt()    # match the prompt 
     out = s.before  # print everything before the prompt, this returns a byte object and could need decode(utf-8) 
     out = out.decode('utf-8') 
     out = out.split() 
     out = out[1] 
     print(type(out)) #These type function give us an easy output of data types in the traceback 
     print(type(ip)) 

     ipdict = dict(out=ip) ###Getting stuck here on two string types. 
     print(ipdict) 
     s.logout() 
    except (pxssh.ExceptionPxssh, pexpect.EOF) as e: 
     pass 

不是傳遞我希望(它實際上將是盒子的主機名),我們得到這樣的輸出字符串...

<class 'str'> 
<class 'str'> 
{'out': '10.20.234.3'} 

Python文檔只給出了密鑰的例子字符串和值爲int。我用這個錯了嗎?

https://docs.python.org/2/tutorial/datastructures.html

在此先感謝。

+0

給出的輸出是「self,ip」的輸入是什麼? – Floris

+0

這是一個類的方法,所以self是對象的當前實例,ip是類似於'10 .20.234.3'的字符串。主機名看起來像這樣的'P-2301'。 – jonnymac

回答

2

使用的字典文字來代替:

ipdict = { out: ip } 

以這種方式調用dict()只是路過命名參數;字典文字採用表達式來表示鍵和表達式的值。

+0

Traceback(使用python3.3)...文件「ipchk_v2.py」,第53行 ipdict = dict {out:ip} ^ SyntaxError:無效的語法 – jonnymac

+0

@jonnymac:比較這兩行。你的這個詞不應該有'dict'。 – Ryan

+0

你是對的,它確實是一個語法錯誤。好多了。 – jonnymac

相關問題