我试图让字典(程序的第一部分生成)写入到csv,以便我可以对excel中的数据执行进一步的操作。我意识到代码效率不高,但在这一点上,我只是喜欢它的工作。我可以在以后加速处理它。将字典数组写入CSV
import csv
import pprint
raw_data = csv.DictReader(open("/Users/David/Desktop/crimestats/crimeincidentdata.csv", "r"))
neighborhood = []
place_count = {}
stats = []
for row in raw_data:
neighborhood.append(row["Neighborhood"])
for place in set(neighborhood):
place_count.update({place:0})
for key,value in place_count.items():
for place in neighborhood:
if key == place:
place_count[key] = place_count[key]+1
for key in place_count:
stats.append([{"Location":str(key)},{"Volume":str(place_count[key])}])
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(stats)
程序仍在这里很好运行的是由pprint输出
[ [{'Location': 'LINNTON'}, {'Volume': '109'}],
[{'Location': 'SUNDERLAND'}, {'Volume': '118'}],
[{'Location': 'KENTON'}, {'Volume': '715'}]
这是错误肯定是发生了明显。该程序将头文件写入csv,然后抛出ValueError。
fieldnames = ['Location', 'Volume']
with open('/Users/David/Desktop/crimestats/localdata.csv', 'w', newline='') as output_file:
csvwriter = csv.DictWriter(output_file, delimiter=',', fieldnames=fieldnames, dialect='excel')
csvwriter.writeheader()
for row in stats:
csvwriter.writerow(row)
output_file.close()
我花了相当多的时间来搜索这个问题,但没有一个我试图使用的建议都工作过。我想我必须要失去一些东西,所以我非常感谢任何和所有的帮助。
Traceback (most recent call last):
File "/Users/David/Desktop/crimestats/statsreader.py", line 34, in <module>
csvwriter.writerow(row)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/csv.py", line 153, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/csv.py", line 149, in _dict_to_list
+ ", ".join([repr(x) for x in wrong_fields]))
ValueError: dict contains fields not in fieldnames: {'Location': 'SABIN'}, {'Volume': '247'}
完美运作。谢谢。我还应该注意到,任何尝试这样做的人都必须编辑最后三行,因为最后的for循环没有正确缩进。 – MobiusCode 2014-10-10 02:07:48
@ DavidKatz-Wigmore - 我刚刚为加速代码添加了一些建议,在标准库中使用了一些Python最有用的函数(和类)。 – rmunn 2014-10-10 02:35:46