I have the following code
for index,(key,value) in enumerate(dict_var.items()):
sorted_dict[index] = (key, value)
print("The sorted list is:{}".format(sorted_dict))
where
- dict_var is a dictionary.
- sorted_dict is a list that stores the keys and values of dict_var in a sorted order.
can anybody explain why this code doesn't work?
I get this error:
sorted_dict[index] = (key, value)
IndexError: list assignment index out of range
You're getting the index error because the len of the
dict_var
is larger than the len of thesorted_dict
. To avoid this error, make certain that the size of the list is larger or the same size as the len of thesorted_dict
. If you could show us what thesorted_dict
looks like before you run the code that would also help. Also, it might not be a good idea to name a listsorted_dict
.sorted_list
would be better. You can also avoid this error with: