[英]Unhashable type: 'list' when using push in pymongo
我目前正在從事 web 抓取項目。 目標是每天檢索加油站 (900+) 中可用的不同類型燃料的價格。 如果價格發生變化,腳本就能將 append 的新價格添加到我的 Mongodb 數據庫中。
收集的數據如下所示:
Price_post_api = {
"station_id": 31200009,
"price_detail": [
{
"fuel_id": 1,
"fuel_name": "Gazole",
"fuel_cost": 1.959,
"update_date": {
"$date": "2022-05-30T10:05:22Z"
}
},
{
"fuel_id": 2,
"fuel_name": "SP95",
"fuel_cost": 2.049,
"update_date": {
"$date": "2022-05-30T10:05:23Z"
}
},
{
"fuel_id": 5,
"fuel_name": "E10",
"fuel_cost": 2.009,
"update_date": {
"$date": "2022-05-30T10:05:23Z"
}
}
]
},
我很難弄清楚如何根據"fuel_cost"
字段正確$push
Mongodb 中的數據。 這里是 db 中預期的 output 的示例。
Mongodb_price_data ={
"station_id": 31200009,
"price_detail": [
{
"fuel_id": 1,
"fuel_name": "Gazole",
"fuel_cost": 1.959,
"update_date": {
"$date": "2022-05-30T10:05:22Z"
}
},
{
"fuel_id": 1,
"fuel_name": "Gazole",
"fuel_cost": 35.87,
"update_date": {
"$date": "2022-05-31T10:09:22Z"
}
},
{
"fuel_id": 2,
"fuel_name": "SP95",
"fuel_cost": 2.049,
"update_date": {
"$date": "2022-05-30T10:05:23Z"
}
},
{
"fuel_id": 2,
"fuel_name": "Gazole",
"fuel_cost": 1.59,
"update_date": {
"$date": "2022-07-14T00:10:19Z"
}
},
{
"fuel_id": 5,
"fuel_name": "E10",
"fuel_cost": 2.009,
"update_date": {
"$date": "2022-05-30T10:05:23Z"
}
}
]
}
到目前為止,我已經創建了以下 function:
def update_new_price(station_id, fuel_id, fuel_name, cost):
query = {'station_id':station_id, 'price_detail.fuel_id':fuel_id, 'price_detail.fuel_name':fuel_name,'price_detail.fuel_cost':cost}
new_value = {
'$push':{
'price_detail':{
[{'price_detail.fuel_id': fuel_id,'price_detail.fuel_name':fuel_name ,'price_detail.fuel_cost':cost}]
}}}
result = db[CL_PRICE].find(query)
if not list(result):
db[CL_PRICE].update_one(query,new_value,upsert= True)
print('new value added')
else:
print('Already exists')
一旦我運行我的代碼,我就會收到一條錯誤消息。
'price_detail':{
TypeError: unhashable type: 'list'
知道為什么以及如何解決它嗎?
我認為你需要在那里移除額外的彎曲支架。
代替
'price_detail':{
[{'price_detail.fuel_id': fuel_id,'price_detail.fuel_name':fuel_name ,'price_detail.fuel_cost':cost}]
}
應該是
'price_detail': [
{'price_detail.fuel_id': fuel_id,'price_detail.fuel_name':fuel_name ,'price_detail.fuel_cost':cost}
]
您實際上是在嘗試創建一個由單個元素組成的集合,該元素是一個列表。 並且 set 只能包含列表不是的可散列對象。
一個最小的可重現示例是
>>> {[1, 2, 3]}
Traceback (most recent call last):
Input In [2] in <cell line: 1>
{[1, 2, 3]}
TypeError: unhashable type: 'list'
中間沒有:
的{}
是創建集合的語法。 為清楚起見,以下是一些創建集合的正確方法的示例。
>>> {(1, 2, 3)} # a set containing a single tuple
{(1, 2, 3)}
>>> {*[1, 2, 3]} # a set of three elements created from a list
{1, 2, 3}
>>> {1, 2, 3} # a set created from three values
{1, 2, 3}
>>> {x for x in range(1, 4)} # a set comprehension expression
{1, 2, 3}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.