I am writing a function to clean data of dictionary which contains a key-value pairs showing a date and the rainfall on that date. The conditions for the cleaning of data requires the removal of and key-value pairs where the values meet the following conditions:
def clean_data (adic):
newDic = {}
for (date,inches) in adic.items():
print (date,inches)
if not type(inches) == float:
if not type(inches) == int:
print ("type")
continue
elif inches < 0:
print ("below 0")
continue
elif inches > 100:
print ("above 100")
continue
else:
print ("added")
newDic[date]=inches
return newDic
rainfall = {"20190101": 5, "20190102": "6", "20190103": 7.5,
"20190104": 0, "20190105": -7, "20190106": 102,
"20190107": 1}
print(clean_data(rainfall))
For some reason my code is outputting:
20190101 5
20190102 6
type
20190103 7.5
added
20190104 0
20190105 -7
20190106 102
20190107 1
{'20190103': 7.5}
So many of the key-value pairs are not behaving with the elif statements as I would expect. I can't figure out for example why the first key-value pair of 20190101 5 passes through all the if/elif statements put is not added to the new dictionary or why the 20190105 -7 key-value pair passes through the elif statement with value less than 0. When I change all these statements to if statements not elif statements the code works but as fair I can tell the statements are mutually exclusive so the elifs should work. I want the code to only run the one if or elif statement that is true, I don't need it to run all of them if one condition is met. I don't understand elifs are not working?
The 5 of 20190101 5
is not float, so it goes into the first branch
if not type(inches) == float:
Since it entered here, it will not enter any elif
s.
The 5 of 20190101 5
is integer, so this part does not execute:
if not type(inches) == int:
print ("type")
continue
If your requirement is
the type is not an integer or a float.
(should actually be: the type is neither integer nor float )
Use if not type(inches) == float and not type(inches) == int:
rainfall = {"20190101": 5, "20190102": "6", "20190103": 7.5,
"20190104": 0, "20190105": -7, "20190106": 102,
"20190107": 1}
5, 0, -7, 102, 1
are type of int
. First if statement of if not type(inches) == float
will handle it, and because they are int, they won't go to if statement if not type(inches) == int:
.
"6"
is string, neither float nor int. So it will print type message.
Only element that will be handled correctly is 7.5
.
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.