How to sort a dictionary in python using enumerate?











up vote
0
down vote

favorite












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











share|improve this question
























  • Possible duplicate of How to resolve IndexError: list assignment index out of range using array inside loop in Python
    – MisterMiyagi
    Nov 11 at 16:45










  • Why do you want to use enumerate? It will simply produce the ordering already present in the dictionary, not sort anything. You can produce a list of the sorted items using sorted(dict_var.items()).
    – MisterMiyagi
    Nov 11 at 16:47










  • You can also treat sorted_dict as a dict, not a list.
    – misantroop
    Nov 11 at 16:50















up vote
0
down vote

favorite












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











share|improve this question
























  • Possible duplicate of How to resolve IndexError: list assignment index out of range using array inside loop in Python
    – MisterMiyagi
    Nov 11 at 16:45










  • Why do you want to use enumerate? It will simply produce the ordering already present in the dictionary, not sort anything. You can produce a list of the sorted items using sorted(dict_var.items()).
    – MisterMiyagi
    Nov 11 at 16:47










  • You can also treat sorted_dict as a dict, not a list.
    – misantroop
    Nov 11 at 16:50













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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











share|improve this question















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








python dictionary enumerate sorteddictionary






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 11 at 17:29









rassar

2,2081929




2,2081929










asked Nov 11 at 16:34









Ari Roth

11




11












  • Possible duplicate of How to resolve IndexError: list assignment index out of range using array inside loop in Python
    – MisterMiyagi
    Nov 11 at 16:45










  • Why do you want to use enumerate? It will simply produce the ordering already present in the dictionary, not sort anything. You can produce a list of the sorted items using sorted(dict_var.items()).
    – MisterMiyagi
    Nov 11 at 16:47










  • You can also treat sorted_dict as a dict, not a list.
    – misantroop
    Nov 11 at 16:50


















  • Possible duplicate of How to resolve IndexError: list assignment index out of range using array inside loop in Python
    – MisterMiyagi
    Nov 11 at 16:45










  • Why do you want to use enumerate? It will simply produce the ordering already present in the dictionary, not sort anything. You can produce a list of the sorted items using sorted(dict_var.items()).
    – MisterMiyagi
    Nov 11 at 16:47










  • You can also treat sorted_dict as a dict, not a list.
    – misantroop
    Nov 11 at 16:50
















Possible duplicate of How to resolve IndexError: list assignment index out of range using array inside loop in Python
– MisterMiyagi
Nov 11 at 16:45




Possible duplicate of How to resolve IndexError: list assignment index out of range using array inside loop in Python
– MisterMiyagi
Nov 11 at 16:45












Why do you want to use enumerate? It will simply produce the ordering already present in the dictionary, not sort anything. You can produce a list of the sorted items using sorted(dict_var.items()).
– MisterMiyagi
Nov 11 at 16:47




Why do you want to use enumerate? It will simply produce the ordering already present in the dictionary, not sort anything. You can produce a list of the sorted items using sorted(dict_var.items()).
– MisterMiyagi
Nov 11 at 16:47












You can also treat sorted_dict as a dict, not a list.
– misantroop
Nov 11 at 16:50




You can also treat sorted_dict as a dict, not a list.
– misantroop
Nov 11 at 16:50












2 Answers
2






active

oldest

votes

















up vote
1
down vote













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





share|improve this answer




























    up vote
    0
    down vote













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





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53250818%2fhow-to-sort-a-dictionary-in-python-using-enumerate%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote













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





      share|improve this answer

























        up vote
        1
        down vote













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





        share|improve this answer























          up vote
          1
          down vote










          up vote
          1
          down vote









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





          share|improve this answer












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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 11 at 16:47









          Paritosh Singh

          4908




          4908
























              up vote
              0
              down vote













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





              share|improve this answer

























                up vote
                0
                down vote













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





                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









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





                  share|improve this answer












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






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 11 at 16:43









                  robert ford

                  336




                  336






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53250818%2fhow-to-sort-a-dictionary-in-python-using-enumerate%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Bressuire

                      Vorschmack

                      Quarantine