Question: I have the following text in a file named `my_text.txt`:

```
David: 2
Barbara: 97.2
David: negative
William:

Lynn: 725
Nancy   : 87
     David:       54
Lewis: 18.30
Sue:   3193.74
James: 41.73

David: 974.1

```

Notice the blank lines and the value that is non-numeric. Here is my code to import the data from the file and create a dictionary:

```
import collections
def make_dictionary(file_name):
    d = collections.defaultdict(float)
    with open(file_name, 'r') as file:
        for line in file:
            line = line.strip()

            # skip blank lines
            if line == '':
                continue

            # split on the colons
            elif ':' in line:
                key, val = line.split(':')

                d[key.strip()] += val.strip()

    return d

make_dictionary('my_text.txt')

```

I would like to be able to increment the values in the dictionary. For example, they key/value pair for David would be:

```
David : 1030.1

```

(the sum of the 3 values in the file)

I'm getting the following error:

```
TypeError: unsupported operand type(s) for +=: 'float' and 'str'

```

Does anything know how to resolve this?

Thanks!

Answer: 
The error caused by the fact that the program is trying to add integer to string,

i.e. David:negative, hence you can use try except to handle.

```
r = []
with open('t.txt', 'r') as file:
    for line in file:
        line = line.strip()
        # skip blank lines
        if line == '':
            continue
        # split on the colons
        elif ':' in line:
            key, val = line.split(':')
            # try converting it into float else set it set as 0. 
            try:
                val = float(val.strip())
            except:
                val = 0
            r.append({'name': key.strip(), 'val': val})

```

then you can sum up like this:

```
d = collections.defaultdict(float)
for item in r:
    d[item['name']] += item['val']

```
You are parsing a text file which has values that are `str`, however you initialize the `defaultdict` with `float` so it expects floats.

```
d[key.strip()] += val.strip()

```

The above should be changed to:

```
d[key.strip()] += float(val.strip())

```

I will leave it up to you to figure out how to handle conversion failures.