I'm very new to python, but learning. I have below error in my code, I could solve 1 of the solutions, but I'm not sure is correct.
1. UnboundLocalError: local variable 'newdict' referenced before assignment
In my function I want to copy data to newdict if [elt['id'] for elt in response_json['data']]
is higher but I get the error number 1. I then googled and found out that I could add Global newdict, but I am not sure if it is the right of way of expressing variables in Python. I am not sure how I can solve it.
I want to copy only the 'data' key from the nested dictionary response_json, it looks like it is a nested dictionary, so I can compare the 'id' element, because if that's higher than the previous, then I need to do something.
I hope someone can help me.
import json
import pprint, datetime
import numpy as np
import schedule
import time
from http import client
trading_pair_id = 48
offset = 0
limit = 1
newdict = {'id': 0} # <--- Not sure I have done this correct
def trades():
global newdict # <--- I'm not sure this is pythonically correct
# call the API `GET trades` endpoint
conn = client.HTTPSConnection("trade.blocktrade.com")
conn.request("GET", "/api/v1/trades/%d?offset=%d&limit=%d" % (trading_pair_id,offset,limit), headers={
'Content-Type': 'application/json',})
response = conn.getresponse()
response_raw = response.read()
try:
response_json = json.loads(response_raw)
pprint.pprint(response_json)
except:
print(response_raw)
print([elt['id'] for elt in response_json['data']])
if [elt['id'] for elt in response_json['data']] > newdict['id']:
newdict = dict(response_json)
print(newdict)
schedule.every(5).seconds.do(trades)
while True:
schedule.run_pending()
time.sleep(1)