我有一個下面的字典,其中定義了相應區域的應用程式 IP 地址。區域是用戶輸入變數,基于我需要在腳本的其余部分處理 IP 的輸入。
app_list=["puppet","dns","ntp"]
dns={'apac':["172.118.162.93","172.118.144.93"],'euro':["172.118.76.93","172.118.204.93","172.118.236.93"],'cana':["172.118.48.93","172.118.172.93"]}
ntp={'asia':["172.118.162.93","172.118.148.93"],'euro':["172.118.76.93","172.118.204.93","172.118.236.93"],'cana':["172.118.48.93","172.118.172.93"]}
puppet={'asia':["172.118.162.2251","1932.1625.254.2493"],'euro':["172.118.76.21","1932.1625.254.2493"],'cana':["172.118.76.21","193.1625.254.249"]}
代碼嘗試
region=raw_input("entee the region:")
for appl in app_list:
for ip in appl[region]:
<<<rest of operations with IP in script>>
當我嘗試上面的代碼時,得到了下面提到的錯誤。我嘗試使用 json 和 ast 模塊將 str 物件轉換為 dict ,但仍然沒有成功。
收到錯誤
TypeError: string indices must be integers, not str
作為python的新手,不確定如何根據區域獲取ip串列
uj5u.com熱心網友回復:
問題 1:你的回圈意味著 app_list 是一個嵌套的字典,它不是
問題2:appl 是字典的鍵,而不是字典的值。
這有效:
app_list={
"puppet": {'asia':["172.118.162.2251","1932.1625.254.2493"],'euro':["172.118.76.21","1932.1625.254.2493"],'cana':["172.118.76.21","193.1625.254.249"]},
"dns": {'apac':["172.118.162.93","172.118.144.93"],'euro':["172.118.76.93","172.118.204.93","172.118.236.93"],'cana':["172.118.48.93","172.118.172.93"]},
"ntp": {'asia':["172.118.162.93","172.118.148.93"],'euro':["172.118.76.93","172.118.204.93","172.118.236.93"],'cana':["172.118.48.93","172.118.172.93"]}
}
region=input("entee the region:")
print("")
for key in app_list:
appl = app_list[key]
if region in appl:
for ip in appl[region]:
print(ip)
else:
print("region not found in appl " str(appl))
輸出
echo "asia" | python3 blubb.py
entee the region:
172.118.162.2251
1932.1625.254.2493
region not found in appl {'apac': ['172.118.162.93', '172.118.144.93'], 'euro': ['172.118.76.93', '172.118.204.93', '172.118.236.93'], 'cana': ['172.118.48.93', '172.118.172.93']}
172.118.162.93
172.118.148.93
uj5u.com熱心網友回復:
問題是在每個回圈中for appl in app_listappl 將是一個字串并且您正在嘗試索引appl[region],因此您正在嘗試用另一個字串索引該字串。但實際上你只想遍歷字典dns,ntp和puppet, 所以你可以這樣做:
dns={'apac':["172.118.162.93","172.118.144.93"],'euro':["172.118.76.93","172.118.204.93","172.118.236.93"],'cana':["172.118.48.93","172.118.172.93"]}
ntp={'asia':["172.118.162.93","172.118.148.93"],'euro':["172.118.76.93","172.118.204.93","172.118.236.93"],'cana':["172.118.48.93","172.118.172.93"]}
puppet={'asia':["172.118.162.2251","1932.1625.254.2493"],'euro':["172.118.76.21","1932.1625.254.2493"],'cana':["172.118.76.21","193.1625.254.249"]}
app_list = [puppet, dns, ntp]
region = input("entee the region:")
for appl in app_list:
for ip in appl.get(region, []):
print(ip)
請注意,1)app_list現在是預定義字典的串列,2) 您應該使用get()字典的方法對區域進行索引,因為該區域可能不存在于給定的字典中,因此您可以默認回傳一個空串列。否則你可能會遇到KeyError.
我希望這就是你要找的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/477315.html
下一篇:將包含串列的嵌套字典展平為字典
