【问题标题】:appending values to Python dictionary将值附加到 Python 字典
【发布时间】:2016-12-30 17:28:46
【问题描述】:

我有一个读取 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']]}

【问题讨论】:

  • 你不需要在b = [row["Asset IP Address"]] 中的外部[]

标签: python list csv dictionary append


【解决方案1】:

您正在尝试重新发明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(),请选择不同的变量名。

【讨论】:

    【解决方案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)   
    

    【讨论】:

    • 您还应该注意您已经修复了b 分配。而且,有一个缩进错误(可能只是一个发布错误,但你已经复制了它)。
    • 是的,我只是复制粘贴,谢谢指出。我看你比我快一点。
    猜你喜欢
    • 2023-02-02
    • 2021-12-21
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 2015-08-22
    • 2020-10-14
    • 1970-01-01
    相关资源
    最近更新 更多