Python 3.x 如何在python中使用相同的键向字典添加值?
我正在尝试将csv文件转换为字典,而不使用熊猫:-Python 3.x 如何在python中使用相同的键向字典添加值?,python-3.x,csv,Python 3.x,Csv,我正在尝试将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', '
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']}
不确定如何在键中包含订单类型,在值中包含该类型的总订单的位置获得所需的输出。我找不到比以下方法更简洁的方法:
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
对象和集合。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))
我试图在hackerrank中运行相同的代码,但得到一个“pandas”模块未找到的错误。我想知道是否还有其他方法。你能用
pip install pandas
安装pandas
吗?我正在尝试解决hackrank()上的一个问题,我不确定pip install pandas是否在那里工作。我如何在字典中存储dict(res)输出,我认为“dict”不是可调用的object@Indiejay88,请始终在关于SO的问题中指定Python版本(作为标记)(Python
category)