Python:将项目添加到字典

时间:2018-06-22 11:10:19

标签: python-3.x dictionary variables

我是python的新手,我正在编写一个脚本来使用传感器和读取时间读取压力。我不知道如何将其添加到字典中,因此时间就是唯一标识符(键)。有人可以帮忙吗?

代码“ print(read_pressures)”的最后一行仅显示最后的读数。我想显示所有100个读数。任何帮助表示赞赏。

import json
import time
from decimal import Decimal

count = 0
while (count < 100):
    current_time=time.time()
    read_pressures = {'Time': current_time, 'pressure': 7} # the pressure value will be changed to the variable with the current pressure.  
    time.sleep(0.01)
    count = count + 1
    print(count ,read_pressures) # 
print(read_pressures)

谢谢

1 个答案:

答案 0 :(得分:1)

您需要在循环外初始化变量。您可以使用dictionary [key]添加,更新或访问值:

import json
import time
from decimal import Decimal

count = 0
read_pressures = {}
while (count < 100):
    current_time=time.time()
    read_pressures[current_time] = 7 # the pressure value will be changed to the variable with the current pressure.  
    time.sleep(0.01)
    count = count + 1
    print(count, read_pressures) # 
print(read_pressures)