Keyerror有2d词典

时间:2016-02-12 15:21:41

标签: python dictionary

我正在尝试单步执行csv并将日期和时间值分配给他们在2d字典中的点。这将是一个以下形式的实例:

连续各列中的

'11 / 02/16'和'23:24'会将“1”加到字典“日期”中标记为“X”的位置{11/01/16 {23:X}。}”

不幸的是,我收到了以下代码的KeyError。

import csv
import sys
from sys import argv
from collections import defaultdict
script, ReadFile = argv

f = open(ReadFile,'r')
l = f.readlines()
f.close()

file_list = [row.replace('\n','').split(',') for row in l]
header = file_list[0]

Total = 0 
Dates = defaultdict(dict)
print Dates

index_variable = header.index('Time')
index_variable2 = header.index('# Timestamp')

for row in file_list[1:]:
    t = row[index_variable][:2]
    d = row[index_variable2][:10]
    if row[index_variable2][:10] in Dates:
        Dates[d][t] = 1
        Total += 1
        print "true"
    else:
        Dates[d] = {}
        Dates[d][t] = 1
        Total =+ 1
        print "false"

 print Dates

如果我用“'Test'”替换局部变量't',代码就可以了,但显然结果不是我想要的。

提前致谢!

更新:如果我将'd'替换为'Test'并保持't'不变,程序完全正常。只有当Dictionary被特别称为'Dates [d] [t]'时,程序才会返回KeyError。

更新2:我已更新上面的代码以显示我的工作。目前,只要没有添加数字,脚本就可以工作/.

Dates[d][t] = 1 #If I change this...
Dates[d][t] += 1 #To this...

发生KeyError。

更新3:

我改变了部分代码......

for row in file_list[1:]:
    t = row[index_variable][:2]
    d = row[index_variable2][:10]
    if d in Dates and t in Dates[d]:
        Dates[d][t] += 1
        print "true"
    else:
        Dates[d][t] = 1
        print "false"

现在脚本运行得非常好。我想这意味着KeyError是因为我不够具体(???)。

1 个答案:

答案 0 :(得分:0)

假设我们上面看到的只是机器上的if格式错误...

我认为问题出在其他地方:

日期是一个带有各种键的词典。

d是输入中“日期”字段的前10个字符

您想要计算在特定日期点击分数的次数。

日期[d]然后是一个字典,其键是几天。

t应该是在特定日期被击中的分钟词典

你还没告诉python Dates [d]也是一本字典。 但你提到了日期[d] [t]。这意味着Dates [d]已经存在,并且它具有可在其中订阅的内容。

我在我的系统上尝试了这个

import csv
import sys
from sys import argv
from collections import defaultdict
#script, ReadFile = argv

#f = open(ReadFile,'r')
#l = f.readlines()
#f.close()

#file_list = [row.replace('\n','').split(',') for row in l]
#header = file_list[0]
file_list = [['Date','Time','Otherstuff'],
             ['2016-02-01','23:12:00','Sillyme1'],
             ['2016-02-01','23:12:04','Sillyme2'],
             ['2016-02-02','22:10:00','Sillyme3']]
header = file_list[0]

Dates = defaultdict(dict)
print(Dates)

index_variable = header.index('Time')
index_variable2 = header.index('Date')

for row in file_list[1:]:
    t = row[index_variable][:2]
    d = row[index_variable2][:10]
    if d in Dates.keys():
        Dates[d][t] +=1
        print("true")
    else:
        Dates[d] = {} #Now Dates[d] contains a dictionary
        Dates[d][t] = 1 ##Now we put the first counter in the Dates[d] dictionary with key t.

print(Dates)

回归是:

defaultdict(,{})

defaultdict(,{'2016-02-01':{'23':2},'2016-02-02':{'22':1}})