【发布时间】:2021-05-04 17:20:55
【问题描述】:
我需要在循环中填写空字典,但我的脚本给了我错误。我该怎么做?谢谢
脚本:
import numpy as np
name = np.asarray(["John", "Peter", "Jan", "Paul"])
score = np.asarray([1, 2, 3, 4])
apdict = {"Name": "null", "Score": "null"}
for name in name:
for score in score:
apdict["Name"][name] = name[name]
apdict["Score"][score] = score[score]
错误:
Traceback (most recent call last):
File "<ipython-input-814-25938bb38ac2>", line 8, in <module>
apdict["Name"][name] = name[name]
TypeError: string indices must be integers
可能的输出:
#possible output 1:
apdict = {["Name": "John", "Score": "1"], ["Name": "Peter", "Score": "3"]}
#possible output2:
apdict = {["Name": "John", "Score": "1", "3", "4"], ["Name": "Paul", "Score": "1"]}
【问题讨论】:
-
请发布您的预期输出。
-
我的问题已更新,我添加了输出。
-
我认为您的输出应该更好地表示为“字典列表”,而不是看起来无效的 Python 语法([...] 包含类似 dict 的内容,但 dict 应包含在
{...}而不是[...]
标签: python python-3.x pandas dictionary