0

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

3

2 Answers 2

1
sorted_dict = [] 
sorted_dict[0] = 1 #IndexError: list assignment index out of range

The index is specifically used to access an existing position in a python list, and does not silently create the list to accomodate out of range indexes. The issue has nothing to do with enumerate.

you can simply use a list's .append() to add items at the end. Example:

sorted_dict = []
for key,value in dict_var.items():
    sorted_dict.append((key, value))

print("The sorted list is:{}".format(sorted_dict))
Sign up to request clarification or add additional context in comments.

Comments

0

You're getting the index error because the len of the dict_var is larger than the len of the sorted_dict. To avoid this error, make certain that the size of the list is larger or the same size as the len of the sorted_dict. If you could show us what the sorted_dict looks like before you run the code that would also help. Also, it might not be a good idea to name a list sorted_dict. sorted_list would be better. You can also avoid this error with:

for key, value in dict_var.items():
    sorted_dict.append((key, value))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.