计数器抛出错误: 类型错误: 不可哈希 类型: 'dict'



我想从列表中删除重复的元素并返回元素重复的时间数

即使我使用列表,但在json格式计数器抛出错误

如果dict inside list不能在这里使用,请让我知道任何快速的替代方案(因为len(all_response)将是6位数)

下面是我的代码:
from collections import Counter
all_response = [
{
"stock_id": 315,
"product_id": 315
},
{
"stock_id": 315,
"product_id": 315
},
{
"stock_id": 1,
"product_id": 1
},
{
"stock_id": 2,
"product_id": 2
},
{
"stock_id": 2,
"product_id": 2
},
{
"stock_id": 6,
"product_id": 6
}]
stock_ids = []
d = Counter(all_response)
for i in all_response:
if i['stock_id'] not in stock_ids:
stock_ids.append({'stock_id':i['stock_id']})
stock_ids.append({'product_count': d[i['stock_id']]})
print(stock_ids)

预期输出:

[
{
"stock_id": 315,
"product_count": 2
},{
"stock_id": 1,
"product_count": 1
},
{
"stock_id": 2,
"product_count": 2
},
{
"stock_id": 6,
"product_count": 1
}]
original_list = [{'stock_id': 315, 'product_id': 315}, {'stock_id': 1, 'product_id': 1}, {'stock_id': 2, 'product_id': 2}, {'stock_id': 2, 'product_id': 2}, {'stock_id': 6, 'product_id': 6}]
intermediate_result = {}
for i in original_list:
if i["stock_id"] in intermediate_result.keys():
intermediate_result[i["stock_id"]] = intermediate_result[i["stock_id"]]+1
else:
intermediate_result[i["stock_id"]] = 1
result = []
for k,v in intermediate_result.items():
result.append({"stock_id": k, "count": v})
print(result)
[{'stock_id': 315, 'count': 1}, {'stock_id': 1, 'count': 1}, {'stock_id': 2, 'count': 2}, {'stock_id': 6, 'count': 1}]

关于代码:

stock_ids = []
d = Counter(all_response)
for i in all_response:
# here is not okay. stock_ids is list of dictionaries
# so you comparing integer id with one of dictionaries
if i['stock_id'] not in stock_ids:
# here is half okay (you appending only id key, without count key)
stock_ids.append({'stock_id':i['stock_id']})
# here is not okay, because you trying to append new element to list
# you should append only once if you want only one dictionary element
stock_ids.append({'product_count': d[i['stock_id']]})

如错误信息所示,Counter不能接受dict作为输入。但是您可以根据您感兴趣的键创建一个项目列表。

d = Counter(x['stock_id'] for x in all_response)
stock_ids = [{'product_id': x, 'product_count': d[x]} for x in d]

相关内容

最新更新