python modifying the elements in a dictionary
Question: So I have a python dictionary called "p", where

    
    
    import nltk, json, cPickle, itertools
    import numpy as np
    p = {key1: nan, key2: 0.1, key3: nan}
    

nan is np.nan.

I want to write a piece of code that if a value in the dictionary is equal to
nan, then it is changed to 0 instead. I wrote the following code:

    
    
    for key,value in p:
     if value == np.nan:
      p[key] = 0
    

However, the compiler returns with an error saying "ValueError: too many
values to unpack"

I also want to sum up all the values in the dictionary after all the nan's
have been converted to 0s, then divide each value by that sum. I wrote

    
    
    normalization_factor = float(sum(p.values()))
    for key, value in p:
    p[key] = value/normalization_factor
    

Again, the compiler returns the ValueError stated above.

Is there a way to fix the error, or a way to go around this error by doing
something else?


Answer: By default, iterating over a dictionary iterates over only the keys. To
iterate over key/value pairs, you need to do `for key, value in p.iteritems()`
(or `p.items()` in Python 3).

However, you will then run into problems because `nan` is not equal to itself.
You should do `if value is np.nan` or `if np.isnan(value)`.

