【问题标题】:Fill python dictionary in loop在循环中填充python字典
【发布时间】: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


【解决方案1】:

如果您想创建一个字典,其中name 中的元素作为键,score 中的元素作为值,基于 2 个 numpy 数组,您可以按如下方式进行:

apdict = dict(zip(name, score))


print(apdict)

{'John': 1, 'Peter': 2, 'Jan': 3, 'Paul': 4}

编辑

根据您新添加的可能输出,我认为最好是“字典列表”而不是看起来像 set 的东西(因为 {... } 立即包含列表)看起来像 lists (因为 [...] 包含一些东西)但那些包含在列表中的东西看起来更像是字典而不是合法的列表项。 “字典列表”的有效格式应如下所示:

[{'Name': 'John', 'Score': 1},
 {'Name': 'Peter', 'Score': 2},
 {'Name': 'Jan', 'Score': 3},
 {'Name': 'Paul', 'Score': 4}]

在这种情况下,可以如下实现:

apdict = [{'Name': k, 'Score': v} for k, v in zip(name, score)]


print(apdict)

[{'Name': 'John', 'Score': 1},
 {'Name': 'Peter', 'Score': 2},
 {'Name': 'Jan', 'Score': 3},
 {'Name': 'Paul', 'Score': 4}]

或者,您也可以使用 Pandas(因为您在问题中标记了 pandas),如下所示:

import pandas as pd

apdict = pd.DataFrame({'Name': name, 'Score': score}).to_dict('records')


print(apdict)

[{'Name': 'John', 'Score': 1},
 {'Name': 'Peter', 'Score': 2},
 {'Name': 'Jan', 'Score': 3},
 {'Name': 'Paul', 'Score': 4}]

【讨论】:

    【解决方案2】:

    您正在尝试使用字符串索引而不是整数来访问元素:

    apdict["Name"][name] = name[name]
    

    name 必须是整数。

    【讨论】:

      猜你喜欢
      • 2022-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 2021-07-06
      • 2016-11-25
      • 2020-06-08
      相关资源
      最近更新 更多