I need fill empty dictionary in loop, but my script give me error. How can I do that operation? Thanks
Script:
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]
The error:
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 outputs:
#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"]}
If you want to create a dict with elements in name
as keys and elements in score
as values, based on the 2 numpy arrays, you can do it as follows:
apdict = dict(zip(name, score))
print(apdict)
{'John': 1, 'Peter': 2, 'Jan': 3, 'Paul': 4}
Based on your newly added possible output, I think it would better be " list of dictionary " instead of something looks like set of something (since {...} immediately encloses lists) that looks like lists (since [...] encloses something) but those something enclosed in list looks more like a dictionary rather than legitimate list items. The valid format of " list of dictionary " should look like below:
[{'Name': 'John', 'Score': 1},
{'Name': 'Peter', 'Score': 2},
{'Name': 'Jan', 'Score': 3},
{'Name': 'Paul', 'Score': 4}]
In this case, you can achieve it as follows:
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}]
Alternatively, you can also use Pandas (as you tagged pandas in the question), as follows:
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}]
You are trying to access the element with an index of string instead of an integer:
apdict["Name"][name] = name[name]
name
needs to be an integer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.