Python- writing a loop that creates appends data to a dictionary of dictionaries with date being the key value?

192 views Asked by At

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.

1

There are 1 answers

0
Anil_M On

You may want to use defaultdict from collections 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).

>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> d
defaultdict(<type 'dict'>, {})
>>> now = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
>>> d[now]= { 'book1' : 'author1', 'book2' : 'author2'}
>>> d
defaultdict(<type 'dict'>, {'2017-12-06 04:11:02': {'book1': 'author1', 'book2': 'author2'}})
>>>