1
$\begingroup$

I have a dictionary as below:

{
   '$175000-199999': nan,
   '$698506': nan
}

I want to convert the nan to 0.50. I tried using dictionary comprehensions {k:v is 0.50 if v == nan else v for (k, v) in dictionary.items()} but it throws an error saying nan is float. How do I fix this?

$\endgroup$
2
  • 2
    $\begingroup$ See if this snippet can help you. $\endgroup$ Jun 22, 2021 at 1:54
  • 2
    $\begingroup$ that worked - Thank you!! $\endgroup$ Jun 22, 2021 at 17:08

1 Answer 1

0
$\begingroup$

With reference to this answer, here's a running example to solve your problem,

nan_obj = float( 'nan' )

# dict as mentioned in the question
dictionary = {
   '$175000-199999': nan_obj,
   '$698506': nan_obj
}

# Loop through key-value pairs
# For different ways to check if a number is NaN, 
# see https://stackoverflow.com/questions/944700/how-can-i-check-for-nan-values
for key , value in dictionary.items():
    if value != value:
        dictionary[ key ] = 0.5
        
print( dictionary )
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.