字典:一个键的附加值也会添加到其他键中

时间:2014-10-09 14:10:58

标签: python dictionary key

我有一个包含36352行的大型Excel文件,其中包含有关盗窃的信息。每行包含事件发生的日期和市政名称。我正在尝试将这个数据集转换成每个城市的日历地图,说明一年中每天有多少盗窃案。

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

接下来,我又制作了另一本字典,其中的键是市政府的名称,价值是日历字典。

E.g:

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个市的日历词典,我会得到非常高的数字(1个城市中有1天176个盗窃案),不同城市的日历地图是相同的。因此,好像我的市政关键不起作用,但我没有任何线索。

有谁知道我做错了什么?

编辑我如何创建词典:

# 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 个答案:

答案 0 :(得分:0)

听起来就像当您创建第二个字典,其中键是市政名称时,每个键都被指定为对同一字典的引用。请参阅以下示例:

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

请注意,test2 [" x"]在测试更改时更改为foo,因为test2是对test的引用,而不是它自己的字典。解?

import copy

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