简体   繁体   中英

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. 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}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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