Changing certain elements of an array into floats in python

Question:

I currently have an array in my program, and each entry in the array is structured like this:

{'ts': '0', 'ph': '308.8', 'am': '-40.408'}

I want to change the numbers, which are currently stored as strings, to floats, but I’m clueless as to how to do it.

Any help would be greatly appreciated!

Asked By: Murray Ross

||

Answers:

A simple dict comprehension is what you are looking for

d= {'ts': '0', 'ph': '308.8', 'am': '-40.408'}
{k:float(v) for k,v in d.items()}
Answered By: mad_

To change the values in-place you could loop over the elements in the list and then each key in the dictionary and change it:

l = [
    {'ts': '0', 'ph': '308.8', 'am': '-40.408'},
    {'ts': '10', 'ph': '100.8', 'am': '-2.0'}
]

for d in l:
    for k in d:
        d[k] = float(d[k])

The list l will then be:

[{'ts': 0.0, 'ph': 308.8, 'am': -40.408},
 {'ts': 10.0, 'ph': 100.8, 'am': -2.0}]

This assumes you want to change every value

Answered By: Mark
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.