python 读取csv文件并将其序列化为字典列表的脚本{column:value}然后可以将dicts用于计数或cr

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 读取csv文件并将其序列化为字典列表的脚本{column:value}然后可以将dicts用于计数或cr相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python
# encoding: utf-8
"""
csvreader.py

2013-08-27

Script that reads a csv file and serializes it into a list of dictionaries {column: value}
The dicts can then be used for counting or to create other stats. 

Note: spaces in file path should be represented simply as spaces (no escapes)

How: substitute the path of **filename** and run the script.
 
"""



import csv

filename = "test.csv"

f = open(filename, 'rU') # rU: http://www.gossamer-threads.com/lists/python/dev/723649

bag = []

try:
    reader = csv.DictReader(f)
    for row in reader:
        bag.append(row)
finally:
    f.close()
  
	
print "There are %d statements" % len(bag)

keys = bag[0].keys()

print "There are %d keys: %s" % (len(keys), ", ".join(["|"+x+"|" for x in keys]))


def getTotUniqueEl(bag, key):
	exit = []
	for x in bag:
		if x[key] not in exit:
			exit += [x[key]]
	return sorted(exit)


for x in keys:
	els = getTotUniqueEl(bag, x)
	print "*" * 10
	print "The key |%s| has %d unique elements" % (x, len(els))
	print els
	
	

以上是关于python 读取csv文件并将其序列化为字典列表的脚本{column:value}然后可以将dicts用于计数或cr的主要内容,如果未能解决你的问题,请参考以下文章

Python读取文件夹下所有csv文件并将数据按文件名写入字典

如何将 csv 文件转换为可作为文本读取的列表列表? Python

将类反序列化为文件并返回列表

如何将 Python 字典序列化为字符串,然后再返回字典?

读取csv字典变成str了怎么办

Python csv库整理(部分)