0

我正在尝试创建一个字典字典,其中每个字典的键是 datetime.now() ,每个键的值是字典。这本字典是从 API 中提取的,我不断地运行循环。它看起来像这样:

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

理论上这应该可行,但是由于某种原因,当我运行此代码时,每个键的值都搞砸了:

{'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': {...}}

当我尝试按键提取时,它仍然不起作用。了解正在发生的事情以及是否有更好的方法来解决这个问题。

4

1 回答 1

1

您可能希望使用defaultdictcollections嵌套字典相关的复杂性的模块。

一旦我们定义了字典的默认字典,您就可以简单地创建一个新的密钥对,其中键now和值是来自 api 的记录。(如下)。

>>> 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'}})
>>>
于 2017-12-06T04:13:33.883 回答