簡體   English   中英

將值附加到Python字典

[英]appending values to Python dictionary

我有一個讀取CSV文件csv文件的腳本

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創建字典。但是我的結果是列表帶有一個額外的括號。 想伸出援手,看看有人有更好的主意或可以幫助我。 結果

{'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']]}

您正在嘗試重塑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不是變量名的最佳選擇-您正在隱藏 內置的dict() ,請選擇其他變量名。

使用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)   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM