ValueError: failed to convert string to float in dictionary

I convert a long dictionary of weekly values ​​to monthly values.

Here is a small dict example:

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

I use this code to sum 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 works 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 get this very annoying message:

ValueError: could not convert string to float

My questions:

a) Is there a way to track the wrong element of a dictionary in order to better understand what is happening?

b) Is there a way I can convert this if statement to a try statement so that it goes through any errors?

+4
2

.

defaultdict, . -, float try None, float.

, None , .

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]))
0
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

, if: else:

+2

Source: https://habr.com/ru/post/1617913/


All Articles