Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将数据组织到嵌套字典中:错误";列表索引必须是整数或片,而不是str";_Python 3.x - Fatal编程技术网

Python 3.x 将数据组织到嵌套字典中:错误";列表索引必须是整数或片,而不是str";

Python 3.x 将数据组织到嵌套字典中:错误";列表索引必须是整数或片,而不是str";,python-3.x,Python 3.x,我试图将数据点存储在一个列表中,该列表中的键与数据点的收集日期相对应(我的文件中的日期介于2到9个月之间)。我希望字典看起来像这样: {year : { month : {day : [datapoint(x24)]}}} 在我加入defaultdict之前,我的代码会报告一个关键错误: File "test_file3.py", line 35, in <module> my_dict[year][month][day].append(float(row[SENSOR]))

我试图将数据点存储在一个列表中,该列表中的键与数据点的收集日期相对应(我的文件中的日期介于2到9个月之间)。我希望字典看起来像这样:

{year : { month : {day : [datapoint(x24)]}}}
在我加入defaultdict之前,我的代码会报告一个关键错误:

File "test_file3.py", line 35, in <module>
  my_dict[year][month][day].append(float(row[SENSOR]))
KeyError: '2018'

。。。或
传感器
(看不到它是什么)是年、月、日都是字符串。我认为这个错误只适用于我试图附加到列表中的值(字典中的值)。年、月、日是我字典中的关键…传感器变量是什么样子的?这似乎是导致问题的原因,可能它不是整数,因此
row[SENSOR]
语法无效。
File "test_file3.py", line 35, in <module>
    my_dict[year][month][day].append(float(row[SENSOR]))
TypeError: list indices must be integers or slices, not str
infile = open('/Users/joshuaclarkgilman/Documents/5G0E3577 4May18-1146.csv', 
'r')
outfile = open('/Users/joshuaclarkgilman/Documents/test_file.csv', 'w')

from collections import defaultdict
my_dict = defaultdict(lambda: defaultdict(list))

#functions here

for row in infile:
row = row.strip()
row = row.split(",")
if row[0] == "\ufeff5G0E3577" or row[0] == "2015 records" or row[0] == "Measurement Time":
   continue
else:
    year = Year_Function(row[0].split("/"))
    month = Month_Function(row[0].split("/"))
    day = Day_Function(row[0].split("/"))

    my_dict[year][month][day].append(float(row[SENSOR]))

infile.close()