【问题标题】:Python- writing a loop that creates appends data to a dictionary of dictionaries with date being the key value?Python-编写一个循环来创建将数据附加到字典字典中,日期为键值?
【发布时间】:2017-12-06 03:16:03
【问题描述】:

我正在尝试创建一个字典字典,其中每个字典的键是 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': {...}}

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

【问题讨论】:

  • 根据您的描述,我认为您想要orders_dict[now] = order_book
  • 这正是问题所在——愚蠢的错误。感谢您的帮助!

标签: python dictionary gdax-api


【解决方案1】:

您可能希望使用 collections 模块中的 defaultdict 来简化与嵌套字典相关的复杂性。

一旦我们定义了字典的默认字典,您就可以简单地创建一个新的密钥对,其中键为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'}})
>>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    • 2021-12-14
    • 1970-01-01
    相关资源
    最近更新 更多