mercredi 28 avril 2021

elif not working on dictionary key-value pairs

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:

  • the type is not an integer or a float. Even if the value is a string that could be converted to an integer (e.g. "5") it should be deleted.
  • the value is less than 0: it's impossible to have a negative rainfall number, so this must be bad data.
  • the value is greater than 100: the world record for rainfall in a day was 71.8 inches
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?

Aucun commentaire:

Enregistrer un commentaire