【发布时间】:2016-04-04 13:27:10
【问题描述】:
这类似于Python creating dynamic global variable from list,但我仍然感到困惑。
我获得了大量半专有格式的 flo 数据。我已经使用 Python 根据需要剥离数据并将数据保存到名为 badactor.json 的 json 文件中,并以以下格式保存:
[saddr as a integer, daddr as a integer, port, date as Julian, time as decimal number]
任意示例[1053464536, 1232644361, 2222, 2014260, 15009]
我想查看每周/每月的 Flo 日志,并在 Julian 日期之前保存所有内容。首先,我想浏览日志并创建一个根据它发生的朱利安日期命名的列表,即2014260,然后将其保存为同名2014260.json。我有以下内容,但它给了我一个错误:
#!/usr/bin/python
import sys
import json
import time
from datetime import datetime
import calendar
#these are varibles I've had to use throughout, kinda a boiler plate for now
x=0
templist2 = []
templist3 = []
templist4 = []
templist5 = []
bad = {}
#this is my list of "bad actors", list is in the following format
#[saddr as a integer, daddr as a integer, port, date as Julian, time as decimal number]
#or an arbitrary example [1053464536, 1232644361, 2222, 2014260, 15009]
badactor = 'badactor.json'
with open(badactor, 'r') as f1:
badact = json.load(f1)
f1.close()
for i in badact:
print i[3] #troubleshooting to verify my value is being read in
tmp = str(i[3])
print tmp#again just troubleshooting
tl=[i[0],i[4],i[1],i[2]]
bad[tmp]=bad[tmp]+tl
print bad[tmp]
尝试创建变量时出现以下错误:
Traceback (most recent call last):
File "savetofiles.py", line 39, in <module>
bad[tmp]=bad[tmp]+tl
KeyError: '2014260'
【问题讨论】:
-
tmp引用的密钥 - 在这种情况下为'2014260'- 在bad中不存在。 -
是否定义了坏床?
-
我错过了什么吗?这似乎不是最小的工作示例,因为我没有看到您在提供的代码中的任何地方都将 bad 定义为字典? (虽然我可能是盲人)
-
如果
bad未定义,它将是NameError。 -
@TigerhawkT3;如果你尝试运行他的代码。他在某个地方定义了不好,并没有在他的 MWE 中显示出来。他遇到的问题是 bad 缺少密钥,在他向我们展示他如何添加到他的字典之前,我们无法说出原因。