类型错误:不可损坏的类型:';dict';在Python中从csv读取
有人能告诉我如何解决这个问题吗? 我得到一个类型错误:不可损坏的类型:“dict” 我的目标是将库存物品展示一次,并增加双倍产品的计数器。 在本例中,橙色:2类型错误:不可损坏的类型:';dict';在Python中从csv读取,python,Python,有人能告诉我如何解决这个问题吗? 我得到一个类型错误:不可损坏的类型:“dict” 我的目标是将库存物品展示一次,并增加双倍产品的计数器。 在本例中,橙色:2 enter code here import argparse import csv from datetime import date # Do not modify these lines __winc_id__ = 'a2bc36ea784242e4989deb157d527ba0' __human_name__ = 'supe
enter code here
import argparse
import csv
from datetime import date
# Do not modify these lines
__winc_id__ = 'a2bc36ea784242e4989deb157d527ba0'
__human_name__ = 'superpy'
# Add your code after this line
# read requested input from file csv file
parser = argparse.ArgumentParser()
parser.add_argument("inputfile", help="insert name of the csv input file")
args = parser.parse_args()
with open(args.inputfile) as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
hist = dict()
for item in reader:
if item in hist:
hist[item]+=1
else:
hist[item]=1
print(hist)
I use this .csv :
enter code here
id,product_name,buy_date,buy_price,expiration_date
1, orange, 2020-01-01, 1, 2020-01-14
2, banana, 2020-01-01, 1, 2020-01-14
3, orange, 2020-01-01, 1, 2020-01-14
4, pizza, 2020-01-01, 1, 2020-01-14
你能给我一些关于如何解决这个问题的建议吗?也许
pandas
可以帮助你简化事情
此代码可以扩展以接受来自argparser的参数,其中args.inputfile
可以传递到pd.read\u csv()
函数中。为了演示,我将示例保持简单
import pandas as pd
# Read the file into a DataFrame.
df = pd.read_csv('/path/to/fruit.csv')
# Count values.
counts = df['product_name'].value_counts().reset_index().to_numpy()
输出:
for f, c in counts:
print(f.strip(), c)
orange 2
pizza 1
banana 1
编辑:该示例经过编辑,因此可以提供字符串输出,而不是数据帧。在向字典添加键时,如果尝试使用不可损坏的键类型,则会出现此错误。在第二个dictionary hist中,您使用另一个dictionary创建了一个dictionary键。因此,您可以像这样修复它
for item in reader:
if item["id"] in hist:
hist[item["id"]]+=1
else:
hist[item["id"]]=1
项
是一个指令
。您不能使用dict
作为dict
中的键。您是否打算使用dict
中的某个值作为dict
的键?在这种情况下,我想从csv中计算桔子的数量,并将计数器设置为2个hist[项目['product_name']]
。?是,但是我得到了TypeError:unhabable类型:“dict”谢谢你的回答,hist中的项目也需要调整……”“hist中的项目也需要调整……”你能解释一下:调整到什么了吗?当我尝试这个时,我仍然得到了:TypeError:unhabable类型:“dict”是的,我忘了更改那一行。当您增加或减少计数器时,您使用的是可散列键(我的答案中的Id),因此您无法检查所有字典,只需检查键即可。条件是:如果hist中的项目[“id”]而不是我所知道的,感谢您的帮助answer@Ruben80-不客气。希望它能帮助你简化事情。