valid = {'Temp': [10, 55], 'rain_percent': [49, 100], 'humidity': [30,50]}
data = {'Temp': 30.45, 'rain_percent': 80.56 }
min_temp , max_temp = valid['Temp']
if not(min_temp <= data['Temp'] <= max_temp):
print "Bad Temp"
min_rain , max_rain = valid['rain_percent']
if not(min_rain <= data['rain_percent'] <= max_rain):
print "It's not going to rain"
This is what I'm doing with the 2 dictionarties I'm having. I know that this check can be further modified. Since both the dictionaries i.e valid
and data
have the same keys
, there must be some better way of implementing this check. Can anyone help me in this?
Thanks a lot.
If I understand the question correctly, you're trying to check if each value data[k]
is in the range defined by the 2-element list/tuple valid[k]
.
Try using a for
loop and dict.items()
to iterate through data
and compare each value to the corresponding range in valid
:
valid = {'Temp': [10, 55], 'rain_percent': [49, 100], 'humidity': [30,50]}
data = {'Temp': 30.45, 'rain_percent': 80.56, 'humidity': 70 }
for key,val in data.items():
min, max = valid[key]
if not( min <= val <= max ):
print "%s=%g is out of valid range (%g-%g)" % (key, val, min, max)
else:
print "%s=%g is in the valid range (%g-%g)" % (key, val, min, max)
In the case of the example data
values I gave, it will print this:
rain_percent=80.56 is in the valid range (49-100)
Temp=30.45 is in the valid range (10-55)
humidity=70 is out of valid range (30-50)