Reputation: 952
I think I have a bug in my python installation. The following code:
i = 0
while i < 100:
for key in F1Test.keys():
mTest = np.append(mTest, float(F1Test[key]))
i = i+1
will run for a random number of times before it crashes giving the following error:
ValueError: could not convert string to float: error
F1Test has the following values:
In [123]: F1Test
Out[123]:
{'AltoFlute': 0.75,
'AltoSax': 1.0,
'Bass': 0.9111111111111111,
'BassClarinet': 0.8,
'BassFlute': 0.8695652173913043,
'BassTrombone': 'error',
'Bassoon': 0.7692307692307692,
'BbClarinet': 0.9230769230769231,
'Cello': 0.8695652173913043,
'EbClarinet': 0.9411764705882353,
'Flute': 0.8695652173913044,
'Guitar': 1.0,
'Horn': 1.0,
'Oboe': 0.8750000000000001,
'Piano': 0.993103448275862,
'SopSax': 0.9230769230769231,
'TenorTrombone': 0.923076923076923,
'Trumpet': 1.0,
'Tuba': 0.888888888888889,
'Viola': 0.8735632183908046,
'Violin': 0.8974358974358975}
I found it in a larger code and got it reduced to this form. Apparently, once every 50th time it will read the values from the dictionary as strings instead of floats. I am using ipython 1.2.1, python 2.7.6 and Ubuntu 14.04.
I am not interested in a workaround (I know I can test for type and be done with it), I just find this interesting and I am looking to understand this problem.
Upvotes: 1
Views: 205
Reputation: 180411
F1Test[key]
gets each value from your dict, then you cast to float with float(F1Test[key])
, you have a string in your dictionary "error"
which you try casting to a float so obviously it will error. There is no way you will ever get the code to run without error unless using a try/except
or some other method to catch input that cannot be cast to a float.
On another note all the values bar "error"
are already floats so casting is redundant, you also don't need to call .keys
to iterate over the dict keys, for key in dict
is sufficient, also if you just want the values use dict.values()
.
Upvotes: 2