My script gets a response from a websocket, the response contains dicts and a list, I need the list. I then need to save the list to a mongodb. I though I though I could use dict(zip) to convert the list to a dict but I get this error: TypeError: unhashable type: 'list'
code:
import json, time
import pandas as pd
import pymongo
from pymongo import MongoClient
from websocket import create_connection
if __name__ == '__main__':
db_name = 'KTDB'
db_collect = 'crypto_data'
client = MongoClient('localhost', 27017)
mydb = client[db_name]
ws = create_connection("wss://ws.kraken.com/")
ws.send(json.dumps({
"event": "subscribe",
"pair": ["BTC/USD"],
"subscription": {"name": "trade"}
}))
timeout = time.time() + 60*1
while time.time() < timeout:
js = json.loads(ws.recv())
if isinstance(js, list):
print(js)
jd = zip(range(len(js)), js)
#jd=dict(zip(js,range(len(js))))
mydb[db_collect].insert_many(jd)
#mydb[db_collect].insert_one({"test": 'check'})
the ws response:
[321, [['47426.40000', '0.01799527', '1613158549.286001', 's', 'l', '']], 'trade', 'XBT/USD']
MongoDB is fundamentally a key/value pair store. It can store lists, but only as the value half of the key/value pair.
So to achieve your objective of storing a list, create a key (dict) and store the list as a value.
if isinstance(js, list):
mydb[db_collect].insert_one({'my_list': js})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.