IndexError: list assignment index out of range in python What am i doing wrong. I am an newbie
actual_ans_dict = []
for data in prsnobj.result:
actual_ans_dict[data[0]] = data[1]
print actual_ans_dict
actual_ans_dict
is an empty list. You are trying to set a value to actual_ans_dict[data[0]]
but an element with this index doesn't exist.
You can change the type of actual_ans_dict
to dict :
actual_ans_dict = {}
for data in prsnobj.result:
actual_ans_dict[data[0]] = data[1]
print actual_ans_dict
This is because your actual_ans_dict
is empty, which means, it has not any indexes yet.
actual_ans_dict = [None]*max([data[0] for data in prsnobj.result]) # not very pythonic, actualy
for data in prsnobj.result:
actual_ans_dict[data[0]] = data[1]
print actual_ans_dict
This will give you the ability to assign a value to a particular index. There is a slightly more correct and shorter way to do it:
actual_ans_dict = [data[1] for data in prsnobj.result]
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.