0

I have this dict :

mydict = {'Andreas': 0.4833775399766172, 'Anh': nan, 'Maryse': 0.61436719272499474, 'Darren': -0.44898819782452443, 'Jesse': 0.14565852997686479, 'Mitchell': nan}

The nan's give me no information at all so I want to filter them out.

for k, v in mydict.iteritems():
    if v == 'nan':
        del mydict[v]

I tried this, but it doesn't work. Could anyone help me? Thanks in advance.

Anna Tol
  • 145
  • 1
  • 1
  • 9
  • Possible duplicate: How to check for NaN in python: http://stackoverflow.com/questions/944700/how-to-check-for-nan-in-python – Kmeixner May 11 '15 at 13:51
  • 1
    What's `nan` here? `float('nan')` or plain string? Why do you modify the dict during iteration? Why do you `del`ete by value (and not the key)? – vaultah May 11 '15 at 13:57

2 Answers2

1

You need to use the key not the value and you cannot delete from a dict you are iterating over, you need to copy:

for k, v in mydict.copy().items():
    if v == "nan":
        del mydict[k]

print(mydict)

Whatever nan actually is whether a string or something else you need to use the key, mydict[v] will give you a keyError and changing the size of the dict will give you a RuntimeError: dictionary changed size during iteration

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

You need to use math.isnan to check the value.

import math
result = {k:v for (k,v) in d.iteritems() if not math.isnan(v)}