Python: misbehaves inside a function - erroneous TypeError
I have dicts that I need to clean up for example.
dict = {
'sensor1': [list of numbers from sensor 1 pertaining to measurements on different days],
'sensor2': [list of numbers from from sensor 2 pertaining to measurements from different days],
etc. }
Several days have bad values, and I would like to generate a new dict with all gauge values ββfrom that bad day to be deleted using the upper limit of the values ββof one of the keys:
def clean_high(dict_name,key_string,limit):
'''clean all the keys to eliminate the bad values from the arrays'''
new_dict = dict_name
for key in new_dict: new_dict[key] = new_dict[key][new_dict[key_string]<limit]
return new_dict
If I run all lines separately in IPython, it works. The bad days are eliminated and the good ones persist. These are both types numpy.ndarray
: new_dict[key]
andnew_dict[key][new_dict[key_string]<limit]
But, when I run clean_high()
, I get the error:
TypeError: Only single element whole arrays can be converted to index
What?
Internally, the clean_high()
type for new_dict[key]
is a string, not an array. Why change the type? Is there a better way to change the dictionary?
source to share
Don't change the dictionary while iterating over it. According to python documentation : "Iterating views when adding or removing entries in the dictionary may result in RuntimeError or not iterate over all entries." Instead, create a new dictionary and modify it, iterating over the old one.
def clean_high(dict_name,key_string,limit):
'''clean all the keys to eliminate the bad values from the arrays'''
new_dict = {}
for key in dict_name:
new_dict[key] = dict_name[key][dict_name[key_string]<limit]
return new_dict
source to share