I'm trying to create a dictionary of dictionaries where the key for each dictionary is datetime.now() and the value for each key is a dictionary. This dictionary is pulled from an API and I'm running the loop on a constant basis. It looks something like this:
orders_dict = {}
sleep_time = 1
crypto = 'BTC' #ETH, LTC
x = 0
while x < 5:
try:
now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
order_book = public_client.get_product_order_book('{}-USD'.format(crypto), level=2)
# Append to dictionaries
orders_dict[now] = orders_dict
x += 1
time.sleep(sleep_time)
except:
continue
In theory this should work, but for some reason when I run this code the values for each key is messed up:
{'2017-12-06 02:44:57': {...},
'2017-12-06 02:44:58': {...},
'2017-12-06 02:45:00': {...},
'2017-12-06 02:45:02': {...},
'2017-12-06 02:45:03': {...}}
And when I try extracting by key it still doesn't work. Appreciate insight in what's going on and if there's a better way to approach this issue.
You may want to use
defaultdict
fromcollections
module that ease of complexity associated with nested dicts.Once we define a defaultdict of dictionary, you can simply create a new key pair with key being
now
and value being record from api. (as below).