Hamed Haddadian Hamed Haddadian - 3 months ago 20
Python Question

appending values to Python dictionary

I have a script that reads a CSV file
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


and after running my script

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)


reads the vulnerability lists and create a dictionary with ips that have that vulnerability.how ever my results are a list that has one extra bracket. wanted to reach out and see anyone has better ideas or can help me out.
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']]}

Answer

Use setdefault(), don't make b a list, and don't use builtins as variable names:

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)