Python 将字符串的dict转换为可索引数组

Python 将字符串的dict转换为可索引数组,python,Python,我有一个字符串的dict(存储为数组),我想将它们转换回原始类型。为什么?我正在读写一个json文件,从文件中读回后需要将它们转换回数组 "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)

我有一个字符串的dict(存储为数组),我想将它们转换回原始类型。为什么?我正在读写一个json文件,从文件中读回后需要将它们转换回数组

  "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]
“KdBP”:“[13,31]”,
“KdV”:“[0.001,0.002]”,
“KiBP”:“[13,31]”,
“千伏”:“[0.01,0.02]”,
“KpBP”:“[13,31]”,
“KpV”:“[0.175,0.225]”
}
b=np.asarray(a[“KdBP”])
印刷品(b)```
=====
```[13, 31]```
果然!
====
```打印(b[0])```
```索引器:数组的索引太多```
什么?!
====
```b=np.asarray(a[“KdBP”])
印刷品(b)
c=np.asarray(a[“KdV”])
印刷品(c)
d=b,c```
====
```[13, 31]
[0.001, 0.002]
(数组('[13,31]',dtype='
np.asarray(“[13,31]”)
返回一个0-d数组,因此
索引器
)。 然而,关于额外的垃圾数组,我认为您只是错过了一个
print(d)

使用:

np.asarray(“[13,31]”)返回一个0-d数组,因此
索引器
。 然而,关于额外的垃圾数组,我认为您只是错过了一个
print(d)

使用:


您想使用ast库进行此转换。有关详细信息,请查看

下面是我用来获取一个新字典的代码,其中键为字符串(未更改),值为列表类型

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)
以下是输出:


您可以看到列表的字符串表示形式类型变成了实际列表。

您想使用ast库进行此转换。有关详细信息,请查看

下面是我用来获取一个新字典的代码,其中键为字符串(未更改),值为列表类型

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)
以下是输出:


您可以看到列表的字符串表示类型变成了实际列表。

这将返回一个错误
到底是什么?这个额外的(数组(“…垃圾?
)是什么。您有一个最简单的工作示例吗?在哪里定义了
a
?这将返回一个错误
到底是什么?这个额外的(数组)是什么(“…垃圾?
。你有一个最简单的工作示例吗?
a
定义在哪里?谢谢!在来到堆栈溢出之前,我花了两个小时在这个问题上。你可以说我是Python新手:谢谢!在来到堆栈溢出之前,我花了两个小时在这个问题上。你可以说我是Python新手:谢谢你的帮助!谢谢你,Richard!谢谢你的帮助!我感谢你,Richard!