How to sort a dictionary in python using enumerate?

663 Views Asked by At

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

2

There are 2 best solutions below

0
On

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))
0
On
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))