aabujamra
aabujamra

Reputation: 4636

ValueError: could not convert string to float in dictionary

I'm converting a long dictionary of weekly values into monthly values.

Here is a small sample of the dict:

weeklydic={'2007-10-21': '56', '2007-10-28': '58', '2011-07-10': '56', '2011-07-16': '56'}

I'm using this code to sum the weekly values of the same month:

monthlydic = {}

for key in weeklydic:  
    k = key[0:7]  
    if (k in weeklydic):  
        monthlydic[k] += float(weeklydic[key])  
    else:  
        monthlydic[k] = float(weeklydic[key])  

In general it is working fine, in this small sample it should return

monthlydic={'2007-10': '114', '2011-07': '112'}

However in one dictionary apparently there is a value that I cannot convert to float, so I'm getting this very annoying message:

ValueError: could not convert string to float

My questions are:

a) Is there a way I can track the wrong item of the dictionary to better understand what is happening?

b) Is there a way I can convert that "if statement" to a "try statement" in a way that it passes by any errors?

Upvotes: 4

Views: 2222

Answers (2)

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24164

weekly_string = weeklydic[key]
try:
    weekly_float = float(weekly_string)
except ValueError as e:
    print('error={error}, key={key}, value="{value}"'.format(
          error=e, key=key, value=weekly_string))
    weekly_float = 0.0

You only need to do this once before, not for both branches of your if: else:

Upvotes: 2

Kevin S
Kevin S

Reputation: 2803

A couple of sugestions.

First, use a defaultdict which saves the initial check for a key. Second, convert to float with try, and return None if not a float.

Whenever None is encountered, save this to a list.

from collections import defaultdict

def convert_float(x):
    try:
        return float(x)
    except:
        return None

monthlydic = defaultdict(float)
problems = []

for key in weeklydic:  
    k = key[0:7]  
    val = convert_float(weeklydic[key])
    if val is not None:
        monthlydic[k] += val
    else:  
        problems.append((k, weeklydic[key]))

Upvotes: 0

Related Questions