繁体   English   中英

循环填充 python 字典

[英]Fill python dictionary in loop

我需要在循环中填写空字典,但我的脚本给了我错误。 我该怎么做? 谢谢

脚本:

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"]}

如果要基于 2 numpy arrays 创建一个 dict,其中name中的元素作为键, score中的元素作为值,可以按如下方式进行:

apdict = dict(zip(name, score))


print(apdict)

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

编辑

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

[{'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}]

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

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

name必须是 integer。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM