我正在尝试将csv文件转换为字典,而不使用熊猫:-
101,Minneapolis,shoes,2,Air
102,Chicago,shoes,1,Air
103,New York,shoes,5,Reebok
104,Punjab,slippers,1,adidas
105,Delhi,slippers,2,crocs
我想以字典形式存储数据:
{'shoes': 8,'slippers':3}
我可以将所需的列隐藏到列表中:
l1 = ['shoes', 'shoes', 'shoes', 'slippers', 'slippers']
l2 = ['2', '1', '5', '1', '2']
我正在使用以下行代码来转换字典中的这两个列表:
for i in range(len(l1)):
dict[l1[i]] = [l2[i]]
但是它给我的输出是:
{'shoes': ['5'], 'slippers': ['2']}
不确定如何在键的订单类型和值中该类型的总订单的位置获得所需的输出。
答案 0 :(得分:2)
除了以下pandas
方法之外,我找不到其他更简洁的方法:
import pandas as pd
df = pd.read_csv('test.csv', header=None, sep=',')
res= df.groupby(2)[3].sum().to_dict()
print(res) # {'shoes': 8, 'slippers': 3}
另一种方法是结合使用csv.reader
对象和collections.defaultdict
:
import csv
from collections import defaultdict
with open('test.csv') as f:
res = defaultdict(int)
for row in csv.reader(f):
res[row[2]] += int(row[3])
print(dict(res))