繁体   English   中英

TypeError: unhashable type: 'dict' in Python 从 csv 读取

[英]TypeError: unhashable type: 'dict' in Python reading from a csv

谁能告诉我如何解决这个问题? 我得到一个 TypeError: unhashable type: 'dict

我的目标是一次显示库存商品并增加双重产品的柜台。 在这种情况下橙色:2

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

你能给我一些建议如何解决这个问题吗?

当您在向字典添加键时尝试使用不可散列的键类型时,您会收到此错误。 在第二个字典 hist 中,您使用另一个字典创建字典键。因此您可以像这样修复它

for item in reader:
    if item["id"] in hist:
        hist[item["id"]]+=1
    else:
        hist[item["id"]]=1

也许pandas可以帮助您简化事情。

可以扩展此代码以接受来自 argparser 的 arguments,其中args.inputfile可以传递到pd.read_csv() function。 为了演示,我使示例保持简单。

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()

Output:

for f, c in counts:
    print(f.strip(), c)

orange 2
pizza 1
banana 1

编辑:
该示例已经过编辑,因此可以提供字符串 output,而不是 DataFrame。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM