简体   繁体   English

如何在while循环中使用时间戳作为键和值填充空字典

[英]how to fill empty dictionary in a while loop with time stamp as key and a value

I have a while loop and i am getting a value from a website every second. 我有一个while循环,我每秒从一个网站上获得价值。 I would like to have a dictionary with a date/timestamp as key and the value from website as value. 我想要一本以日期/时间戳为键,而网站的值为值的字典。 As it is a loop, each key/value pair will need to be appended to dictionary. 由于这是一个循环,因此每个键/值对都需要附加到字典中。 Thank you in advance. 先感谢您。

d = {}
x=1
while x < 9:
time.sleep(1)
d.append(dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) #this is key
d.append(website_var) #this is value
x = x+1
print(d)

{1/1/18 10:20:25 : 77.60, 1/1/18 10:20:26 : 77.65, etc:etc} {1/1/18 10:20:25:77.60,1/1/18 10:20:26:77.65等:等}

Try this code 试试这个代码

import datetime
import time

d = {}
x=1
website_var = 'Some Value'
while x < 9:
    time.sleep(1)
    d[datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")] = website_var
    x = x+1
print(d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM