简体   繁体   中英

python modifying the elements in a dictionary

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?

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM