2014-10-09 53 views
0

我有一个很大的Excel文件,包含36352行,包含盗窃信息。每行包含一个日期和发生事件的市政府的名称。我试图将这个数据集转换为每个城市的日历地图,说明一年中每天有多少盗窃案。词典:增加一个键的价值也被添加到其他键

我首先创建了一个日历地图(字典),其中日期是关键,值是盗窃的数量(初始化为0):{day1: 0, day2: 0}

接下来我做了另一个字典,其中的键是城市的名称和值是日历字典。

例如为:

Dictionary['New York'] = {day1: 0, day2: 0, day3: 0} 

这个初始化工作正常。

下一步我带是去通过排我的数据集行(写入content_split),把全市的名称和事件作为键的日期,并加1的值:

Dictionary[name-in-column-14-of-excel-file][day-of-event] += 1 

我写了这是一个循环:

for k in range(1,len(excelfile)): #for all rows in the excel file 
    # datetime.datetime(year,month,day) 
    d = datetime.datetime(int(content_split[k][9]),int(content_split[k][8]),int(content_split[k][7])) 
    # Dictionary[name-of-municipality][timestamp-in-utc] += 1 
    Municipality_dict[content_split[k][14]][calendar.timegm(d.timetuple())] += 1 

如果我再看看日历字典1个市,我得到非常高的数字(176起入室盗窃案1天1个市)和不同城市的日历地图是相同的。因此,我的市政钥匙似乎不起作用,但我不知道。

有谁知道我在做什么错?

编辑对我如何创建的字典:

# Open map containing the days 
with open('days.csv') as f1: 
    days_temp = f1.readlines() 

alldays = [] 

# Get dd;mm;yy format to [dd, mm, yy] format 
for day in days_temp: 
    alldays.append(day.strip().split(';')) 

Timestamp = {} 

# Convert days into UTC codes 
for i in range(len(alldays)): 
d = datetime.datetime(int(alldays[i][2]),int(alldays[i][1]),int(alldays[i][0])) 

# dictionary[UTC-time-code] = 0 (no burglaries occurred) 
Timestamp[calendar.timegm(d.timetuple())] = 0 

# Open file with names of municipalities 
with open('file2.csv') as f2: 
    municipalities_temp = f2.readlines() 

municipalities_dict = {} 

# dictionary[name-of-municipality] = calendar 
for instance in municipalities_temp: 
    municipalities_dict[instance.strip()] = Timestamp 
+1

你是如何创建这些字典的?您正在共享引用,并且只有*一个*字典,而不是单独的对象。 – 2014-10-09 14:14:55

+2

如果你做了类似'd = {'day1':0,...}; M_D ['纽约'] = d; M_D ['Boston'] = d; ...',你会看到你得到的结果。 – chepner 2014-10-09 14:16:36

+0

我编辑了我原来的帖子。我一开始并不理解“共享引用”部分,但现在在ErlVolton的回复中,我明白你的意思。 :) – Jolien 2014-10-09 14:42:07

回答

0

这听起来像当你创建你的密钥是本市名第二字典,每个关键是让分配为相同的参考字典。请参见下面的示例:

>>> test = {"x":"y"} 
>>> test2 = test 
>>> test["x"] = "foo" 
>>> test2 
{'x': 'foo'} 
>>> 

注意test2的[“X”]改变时测试改变,因为test2的是测试参考富,而不是它自己的字典。解?

import copy 

template_dict = {day1: 0, day2: 0, day3: 0} 
Dictionary['New York'] = copy.deepcopy(template_dict) 
+0

太棒了!这工作! – Jolien 2014-10-09 14:40:11

+0

@Jolien。另外,也可以使用'template_dict = lambda:{day1:0,day2:0,day3:0}'来代替复制,然后将其用作Dictionary ['New York'] = template_dict()'(假设这些键应该是'day1','day2'和'day3') – 2014-10-09 14:41:06

相关问题