-1

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!

  • @komatiraju032: "...each entry *in the array*..." – Scott Hunter Apr 20 '20 at 19:21
  • @ScottHunter still likely not an array. List and array are different in Python – Mad Physicist Apr 20 '20 at 19:23
  • That is a pretty unhelpful dupe for this question @yatu. – Mark Apr 20 '20 at 19:27
  • Does [this](https://stackoverflow.com/a/50433921/9698684) not solve the *same* problem? @MarkMeyer – yatu Apr 20 '20 at 19:28
  • @yatu, yes, that's probably helpful — assuming the OP knows how to get each dictionary out of the list. – Mark Apr 20 '20 at 19:31
  • It just seemed like quite a clear dupe imo @MarkMeyer Its just a matter of adding another level of iteration. Quite possibly we'd also find dupes for list of dicts – yatu Apr 20 '20 at 19:44
  • @MadPhysicist: Sure, in that lists exist in Python and arrays do not. – Scott Hunter Apr 20 '20 at 22:10
  • @MarkMeyer. Given that OP hasn't posted a concrete issue beyond asking for someone to do the work for them, I'd vote to close the question regardless. – Mad Physicist Apr 20 '20 at 23:08
  • @MadPhysicist I have no objection to closing the question and haven't voted to reopen. But I think if you are going to use the dupe hammer, it should be a good dupe for the next person that finds this. If it should be closed because it's a bad question, then vote with one of the other reasons. Maybe quarantine just has me extra-grumpy. – Mark Apr 20 '20 at 23:11
  • 1
    @MarkMeyer. That sounds fair. I know I've been extra grumpy myself – Mad Physicist Apr 21 '20 at 00:29

2 Answers2

2

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()}
mad_
  • 8,121
  • 2
  • 25
  • 40
2

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

Mark
  • 90,562
  • 7
  • 108
  • 148