[英]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.