2015-05-18 121 views
0

我想做低于python.The CSV文件:从csv文件创建一本词典?

item1,item2,item2,item3 
item2,item3,item4,item1 

我想要一本字典具有独特的键物品1,项目2,项目3和ITEM4。 dictionary = {item1:value1,item2:value2 ....}。值是密钥在csv文件中出现的次数。如何才能做到这一点?

+0

如何是你开始一个新的线程之前检查可能的重复?!... http://stackoverflow.com/questions/14091387/creating-a -dictionary-from-a-csv-file http://stackoverflow.com/questions/6740918/creating-a-dictionary-from-a-csv-file – Roboticist

回答

1

cvs获得所有项目的列表:

with open('your.csv') as csv: 
    content = csv.readlines() 
    items = ','.join(content).split(',') 

然后启动映射

mapping = {} 
for item in items: 
    mapping[item] = (mapping.get(item) or 0) + 1 

和你将得到如下:

>>> mapping 
{'item2': 3, 'item3': 2, 'item1': 2, 'item4': 1} 
0
import csv 

    temp = dict() 
    with open('stackoverflow.csv', 'rb') as f: 
     reader = csv.reader(f) 
     for row in reader: 
      for x in row: 
       if x in temp.keys(): 
        temp[x] = int(temp[x]) + 1 
       else: 
       temp[x] = 1 
    print temp 

的输出如下所示: -

{'item2': 3, 'item3': 2, 'item1': 2, 'item4': 1} 
1
import csv 
from collections import Counter 

# define a generator, that will yield you field after field 
# ignoring newlines: 
def iter_fields(filename): 
    with open(filename, 'rb') as f: 
     reader = csv.reader(f) 
     for row in reader: 
      for field in row: 
       yield field 

# now use collections.Counter to count your values: 
counts = Counter(iter_fields('stackoverflow.csv')) 

print counts 
# output: 
# Counter({'item3': 2, 'item2': 2, 'item1': 1, 
# ' item1': 1, ' item2': 1, 'item4': 1}) 

看到https://docs.python.org/2/library/collections.html#collections.Counter