我正在嘗試為強化防火墻自動化一些無聊的猴子作業。我收到創建地址物件的請求,例如為 100 個不同的主機..其中許多應該屬于同一個地址組。我的 csv 是
name,address,group
aix01,10.0.0.1,AIXGROUP1
aix02,10.0.0.2,AIXGROUP1
aix02,10.0.0.3,AIXGROUP2
aix245,10.0.0.4,AIXGROUP2
如上所示,有 2x 個組,每個組中有 2 個主機。
我想將組名稱“AIXGROUP1”和“AIXGROUP2”作為字典鍵,并將每個相應 IP 的串列作為其值。所以,它應該是 {AIXGROUP1:[10.0.0.1,10.0.0.2], AIXGROUP2:[10.0.0.3,10.0.0.4]} 然后我會將這個字典傳遞給一個列印命令的函式。這是代碼
with open('hosts.csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
Dictionary = {}
for each in reader:
if len(each[2])!=0:
Dictionary[each[2]] = []
在這一點上,我只有一個字典,其中包含正確的鍵和空串列作為值..這就是我被卡住的地方..如何用 ip 地址填充這些空串列?感覺離勝利只差一步了!:)
uj5u.com熱心網友回復:
您已經接近解決方案了。您唯一需要添加的是檢查該鍵是否已存在于字典中,因此您不要覆寫它,然后添加一行將該值添加到串列中。next(reader, None)如果您不想要字典中的標題行,您可以添加該行。這樣的事情應該作業:
with open('hosts.csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
next(reader, None) # To skip the header row
Dictionary = {}
for each in reader:
if len(each[2])!=0 and each[2] not in Dictionary.keys(): # To not overwrite keys that already exist
Dictionary[each[2]] = []
Dictionary[each[2]].append(each[1]) #To add the values
uj5u.com熱心網友回復:
你的回圈需要根據組名稱是否已在詞典或沒有,像這樣(我將用它來采取不同的行動d,而不是Dictionary為了簡潔):
group = each[2]
ip = each[1]
if group in d:
d[group].append(ip) # Append another IP to the list
else:
d[group] = [ip] # Initialize list with first element
uj5u.com熱心網友回復:
我會這樣做:
result = {}
for row in reader:
if len(row[2])!=0:
try:
result[row[2]].append(row[1])
except:
result[row[2]] = [row[1]]
result
>>> {'AIXGROUP1': ['10.0.0.1', '10.0.0.2'], 'AIXGROUP2': ['10.0.0.3', '10.0.0.4']}
這種方法創建串列并在同一個回圈中填充它們。該try / except邏輯是不是有條件的速度更快,是這樣的:
- 對于每一行資料,嘗試將地址附加到正確的組中。
- 如果引發例外,則字典中尚不存在該鍵,因此我們必須創建它。
- 在創建密鑰時,我們將密鑰定義為一個串列,其中包含一個元素,即當前地址。
- 如果未引發例外,則字典已經有該鍵的一個地址,因此我們只需將下一個地址附加到該鍵參考的串列中。
請注意,命名輸出dict字典可能不是最佳做法。另外,如果您要使用csv.read(),請不要忘記跳過標題行!
uj5u.com熱心網友回復:
import csv
# create the dictionary in which your data will be stored
ip_dict = {}
# open the wanted file
with open('hosts.csv', 'r') as csvfile:
# read the csv data
csv_reader = csv.reader(csvfile, delimiter=',')
# skip the header
next(csv_reader)
# parse your data
for _, ip, name in csv_reader:
# do whatever you need only if name is not empty
if name:
# if there is already an entry in the dictionary then append to it
if name in ip_dict:
ip_dict[name].append(ip)
# if there is not create a list with the current ip as the first entry
else:
ip_dict[name] = [ip]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347781.html
下一篇:如何檢查嵌套字典中的值是否相等
