0

I have a dict of strings (stored as arrays) and I'd like to convert them back to their original type. Why? I'm reading and writing a json file and need to convert them back into arrays after reading it back from file.

  "KdBP": "[13, 31]",
  "KdV": "[0.001, 0.002]",
  "KiBP": "[13, 31]",
  "KiV": "[0.01, 0.02]",
  "KpBP": "[13, 31]",
  "KpV": "[0.175, 0.225]"
}

b = np.asarray(a["KdBP"])
print(b)```

=====
```[13, 31]```

As expected!
====

```print(b[0])```

```IndexError: too many indices for array```

What?!
====
```b = np.asarray(a["KdBP"])
print(b)

c = np.asarray(a["KdV"])
print(c)
d = b,c```
====
```[13, 31]
[0.001, 0.002]
(array('[13, 31]', dtype='<U8'), array('[0.001, 0.002]', dtype='<U14'))```

What the heck? What's this extra (array('... garbage?

All I'm trying to do is convert the string "[13.25, 31.21]" to an indexable array of floats --> [13.25, 31.21]
zorrobyte
  • 21
  • 5
  • 1
    This will return an error `What the heck? What's this extra (array('... garbage?`. Do you have a minimal working example? Where is `a` defined? – tommy.carstensen May 06 '19 at 22:07

2 Answers2

1

np.asarray("[13, 31]") returns a 0-d array, hence that IndexError. While, about the extra, garbage array, I think you simply missed a print(d) somewhere.

Use np.fromstring:

b = np.fromstring(a["KdBP"].strip(" []"), sep=",")

>>> print(b[0])
13.0
Lante Dellarovere
  • 1,838
  • 2
  • 7
  • 10
  • THANK YOU! I spent two hours on this before coming to Stack Overflow. You could say I'm new to Python :D – zorrobyte May 06 '19 at 22:41
1

You want to use the ast library for this conversion. Check out this answer for more details.

Below is the code I used to get a new dictionary with the keys as strings (unchanged) and the values as list types.

import ast
test_dict = {  "KdBP": "[13, 31]",
  "KdV": "[0.001, 0.002]",
  "KiBP": "[13, 31]",
  "KiV": "[0.01, 0.02]",
  "KpBP": "[13, 31]",
  "KpV": "[0.175, 0.225]"
}

for value in test_dict:
    print(type(test_dict[value]))
    converted_list = ast.literal_eval(test_dict[value])

    print(type(converted_list)) #convert string list to actual list
    new_dict = {value: converted_list}

    print(new_dict)

Here is the output:

enter image description here

You can see that the type of the string representation of your list becomes an actual list.

Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Richard K Yu
  • 2,152
  • 3
  • 8
  • 21