0

I'm pretty new to python and I'm writing a script to read pressures using a sensor with the time of the reading. I don't know how to add this to a dictionary so the time is the unique identifier (the key). Can anyone help?

The last line of code "print(read_pressures)" just displays the last reading. I want to show all 100 readings. Any help appreciated.

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)

Thanks

resolver101
  • 2,155
  • 11
  • 41
  • 53
  • Possible duplicate of [Add new keys to a dictionary?](https://stackoverflow.com/questions/1024847/add-new-keys-to-a-dictionary) – Jesse Jun 22 '18 at 11:18

1 Answers1

1

You need to initialize the variable outside the loop. You use dictionary[key] to add, update or access values:

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)
cosarara97
  • 115
  • 2
  • 5
  • Just for my understanding, the "current_time" in read_pressures[current_time] is the key and the "7" is the value? – resolver101 Jun 22 '18 at 13:50