我在下面提供了CSV文件
CODE,PRODUCT
101,item_1
101,item_1
101,item_2
102,item_3
103,item_2
104,item_5
我需要转换成下面给出的字典
{101:{'item_1':2, 'item_2':1},
102:{'item_3':1},
103:{'item_2':1},
104:{'item_5':1}
我已使用CSV读取文件
import csv
def csv_reader(file_obj):
reader = csv.reader(file_obj)
for row in reader:
print(" ".join(row))
if __name__ == "__main__":
csv_path = 'g.csv'
with open(csv_path, "r") as f_obj:
csv_reader(f_obj)
如何转换为词典
{101:{'item_1':2, 'item_2':1},
102:{'item_3':1},
103:{'item_2':1},
104:{'item_5':1}
答案 0 :(得分:2)
由于每行都是从csv.reader
返回的字符串列表,因此您应该尝试如下操作:
result_dict = {}
for row in reader:
if row[0] in result_dict:
if row[1] in result_dict[row[0]]:
result_dict[row[0]][row[1]] += 1
else:
result_dict[row[0]][row[1]] = 1
else:
result_dict[row[0]] = {row[1]:1}
注意:这只是一个逻辑概述。请根据需要将其适当地放入代码中,并进行其他检查。
答案 1 :(得分:1)
from collections import defaultdict, Counter
parsed = defaultdict(Counter)
reader = csv.reader(file_obj)
code_index = 0
product_index = 1
for row in reader:
if row and len(row) >= 2:
code = row[code_index]
product = row[product_index]
parsed[code][product] += 1
我认为这可以完成工作。
答案 2 :(得分:0)
礼貌:@monkut
import csv
from collections import defaultdict, Counter
parsed = defaultdict(Counter)
file_obj = open(r'C:\Users\maws\Desktop\g.csv', 'r')
reader = csv.reader(file_obj)
code_index = 0
product_index = 1
next(file_obj)
for row in file_obj:
row = row.split(',')
#print (row)
if row and len(row) >= 2:
code = row[code_index]
#print(code)
product = row[product_index]
parsed[code][product.strip()] += 1
parsed