我有一个读取CSV文件的脚本 csv file
Asset IP Address,Vulnerability Title
50.103.128.11,Partition Mounting Weakness
10.103.128.11,UDP IP ID Zero
10.103.128.11,Root's umask value is unsafe
0.103.128.11,Root's umask value is unsafe
20.103.128.11,Root's umask value is unsafe
10.103.128.11,ICMP timestamp response
22.103.128.11,ICMP timestamp response
10.103.128.11,UDP IP ID Zero
10.103.129.11,Partition Mounting Weakness
并在运行我的脚本后
import csv
from pprint import pprint
#with open('test.csv', 'rb') as f:
# reader = csv.DictReader(f, delimiter=',')
# for row in reader:
# print row
#dict = {a:[], b:[]}
dict = {}
with open('test.csv', 'rb') as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
a = row["Vulnerability Title"]
b = [row["Asset IP Address"]]
#b = row(["Asset IP Address"])
#dict = {a:[], b:[]}
if a in dict:
#print row["Vulnerability Title"]
#if row["Vulnerability Title"] in dict:
dict[a].append(b)
else:
dict[a] = b
pprint(dict)
读取漏洞列表并使用具有该漏洞的ips创建字典。我的结果是一个包含一个额外括号的列表。想伸出手,看到有人有更好的想法,或者可以帮助我。 results
{'ICMP timestamp response': ['10.103.128.11', ['22.103.128.11']],
'Partition Mounting Weakness': ['50.103.128.11', ['10.103.129.11']],
"Root's umask value is unsafe": ['10.103.128.11',
['0.103.128.11'],
['20.103.128.11']],
'UDP IP ID Zero': ['10.103.128.11', ['10.103.128.11']]}
答案 0 :(得分:2)
您正在尝试重新发明defaultdict
:
from collections import defaultdict
d = defaultdict(list)
with open('test.csv', 'rb') as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
d[row["Vulnerability Title"]].append(row["Asset IP Address"])
pprint(d)
作为旁注,dict
不是变量名称的最佳选择 - 您遮蔽 built-in dict()
,选择其他变量名称。
答案 1 :(得分:2)
使用setdefault()
,不要将b
列入清单,也不要将内置字符用作变量名称:
d = {}
with open('test.csv', 'rb') as f:
reader = csv.DictReader(f, delimiter=',')
for row in reader:
a = row["Vulnerability Title"]
b = row["Asset IP Address"]
d.setdefault(a, []).append(b)