Create a dictionary by zipping together two lists of uneven length












10














I have two lists different lengths, L1 and L2. L1 is longer than L2. I would like to get a dictionary with members of L1 as keys and members of L2 as values.



As soon as all the members of L2 are used up. I would like to start over and begin again with L2[0].



L1 = ['A', 'B', 'C', 'D', 'E']    
L2 = ['1', '2', '3']
D = dict(zip(L1, L2))
print(D)


As expected, the output is this:



{'A': '1', 'B': '2', 'C': '3'}


What I would like to achieve is the following:



{'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}









share|improve this question









New contributor




Mat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    10














    I have two lists different lengths, L1 and L2. L1 is longer than L2. I would like to get a dictionary with members of L1 as keys and members of L2 as values.



    As soon as all the members of L2 are used up. I would like to start over and begin again with L2[0].



    L1 = ['A', 'B', 'C', 'D', 'E']    
    L2 = ['1', '2', '3']
    D = dict(zip(L1, L2))
    print(D)


    As expected, the output is this:



    {'A': '1', 'B': '2', 'C': '3'}


    What I would like to achieve is the following:



    {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}









    share|improve this question









    New contributor




    Mat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      10












      10








      10







      I have two lists different lengths, L1 and L2. L1 is longer than L2. I would like to get a dictionary with members of L1 as keys and members of L2 as values.



      As soon as all the members of L2 are used up. I would like to start over and begin again with L2[0].



      L1 = ['A', 'B', 'C', 'D', 'E']    
      L2 = ['1', '2', '3']
      D = dict(zip(L1, L2))
      print(D)


      As expected, the output is this:



      {'A': '1', 'B': '2', 'C': '3'}


      What I would like to achieve is the following:



      {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}









      share|improve this question









      New contributor




      Mat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I have two lists different lengths, L1 and L2. L1 is longer than L2. I would like to get a dictionary with members of L1 as keys and members of L2 as values.



      As soon as all the members of L2 are used up. I would like to start over and begin again with L2[0].



      L1 = ['A', 'B', 'C', 'D', 'E']    
      L2 = ['1', '2', '3']
      D = dict(zip(L1, L2))
      print(D)


      As expected, the output is this:



      {'A': '1', 'B': '2', 'C': '3'}


      What I would like to achieve is the following:



      {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}






      python list dictionary zip






      share|improve this question









      New contributor




      Mat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Mat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 5 hours ago









      coldspeed

      121k21121204




      121k21121204






      New contributor




      Mat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 9 hours ago









      MatMat

      595




      595




      New contributor




      Mat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Mat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Mat is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.
























          4 Answers
          4






          active

          oldest

          votes


















          13














          Use itertools.cycle to cycle around to the beginning of L2:



          from itertools import cycle
          dict(zip(L1, cycle(L2)))
          # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}




          In your case, concatenating L2 with itself also works.



          # dict(zip(L1, L2 * 2))
          dict(zip(L1, L2 + L2))
          # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}





          share|improve this answer































            14














            Use itertools.cycle:



            from itertools import cycle

            L1 = ['A', 'B', 'C', 'D', 'E']
            L2 = ['1', '2', '3']

            result = dict(zip(L1, cycle(L2)))

            print(result)


            Output



            {'E': '2', 'B': '2', 'A': '1', 'D': '1', 'C': '3'}


            As an alternative you could use enumerate and index L2 modulo the length of L2:



            result = {v: L2[i % len(L2)] for i, v in enumerate(L1)}
            print(result)





            share|improve this answer





























              9














              cycle is fine, but I shall add this modulo based approach:



              {L1[i]: L2[i % len(L2)] for i in range(len(L1))]}





              share|improve this answer





























                5














                You can also use a collections.deque() to create an circular FIFO queue:



                from collections import deque

                L1 = ['A', 'B', 'C', 'D', 'E']
                L2 = deque(['1', '2', '3'])

                result = {}
                for letter in L1:
                number = L2.popleft()
                result[letter] = number
                L2.append(number)

                print(result)
                # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}


                Which pops the left most item currently in L2 and appends it to the end once the number is added to the dictionary.



                Note: Both collections.deque.popleft() and collections.deque.append() are O(1) operations, so the above is still O(N), since you need to traverse all the elements in L1.






                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',
                  autoActivateHeartbeat: false,
                  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
                  });


                  }
                  });






                  Mat is a new contributor. Be nice, and check out our Code of Conduct.










                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54095758%2fcreate-a-dictionary-by-zipping-together-two-lists-of-uneven-length%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  4 Answers
                  4






                  active

                  oldest

                  votes








                  4 Answers
                  4






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  13














                  Use itertools.cycle to cycle around to the beginning of L2:



                  from itertools import cycle
                  dict(zip(L1, cycle(L2)))
                  # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}




                  In your case, concatenating L2 with itself also works.



                  # dict(zip(L1, L2 * 2))
                  dict(zip(L1, L2 + L2))
                  # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}





                  share|improve this answer




























                    13














                    Use itertools.cycle to cycle around to the beginning of L2:



                    from itertools import cycle
                    dict(zip(L1, cycle(L2)))
                    # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}




                    In your case, concatenating L2 with itself also works.



                    # dict(zip(L1, L2 * 2))
                    dict(zip(L1, L2 + L2))
                    # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}





                    share|improve this answer


























                      13












                      13








                      13






                      Use itertools.cycle to cycle around to the beginning of L2:



                      from itertools import cycle
                      dict(zip(L1, cycle(L2)))
                      # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}




                      In your case, concatenating L2 with itself also works.



                      # dict(zip(L1, L2 * 2))
                      dict(zip(L1, L2 + L2))
                      # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}





                      share|improve this answer














                      Use itertools.cycle to cycle around to the beginning of L2:



                      from itertools import cycle
                      dict(zip(L1, cycle(L2)))
                      # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}




                      In your case, concatenating L2 with itself also works.



                      # dict(zip(L1, L2 * 2))
                      dict(zip(L1, L2 + L2))
                      # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 4 hours ago

























                      answered 9 hours ago









                      coldspeedcoldspeed

                      121k21121204




                      121k21121204

























                          14














                          Use itertools.cycle:



                          from itertools import cycle

                          L1 = ['A', 'B', 'C', 'D', 'E']
                          L2 = ['1', '2', '3']

                          result = dict(zip(L1, cycle(L2)))

                          print(result)


                          Output



                          {'E': '2', 'B': '2', 'A': '1', 'D': '1', 'C': '3'}


                          As an alternative you could use enumerate and index L2 modulo the length of L2:



                          result = {v: L2[i % len(L2)] for i, v in enumerate(L1)}
                          print(result)





                          share|improve this answer


























                            14














                            Use itertools.cycle:



                            from itertools import cycle

                            L1 = ['A', 'B', 'C', 'D', 'E']
                            L2 = ['1', '2', '3']

                            result = dict(zip(L1, cycle(L2)))

                            print(result)


                            Output



                            {'E': '2', 'B': '2', 'A': '1', 'D': '1', 'C': '3'}


                            As an alternative you could use enumerate and index L2 modulo the length of L2:



                            result = {v: L2[i % len(L2)] for i, v in enumerate(L1)}
                            print(result)





                            share|improve this answer
























                              14












                              14








                              14






                              Use itertools.cycle:



                              from itertools import cycle

                              L1 = ['A', 'B', 'C', 'D', 'E']
                              L2 = ['1', '2', '3']

                              result = dict(zip(L1, cycle(L2)))

                              print(result)


                              Output



                              {'E': '2', 'B': '2', 'A': '1', 'D': '1', 'C': '3'}


                              As an alternative you could use enumerate and index L2 modulo the length of L2:



                              result = {v: L2[i % len(L2)] for i, v in enumerate(L1)}
                              print(result)





                              share|improve this answer












                              Use itertools.cycle:



                              from itertools import cycle

                              L1 = ['A', 'B', 'C', 'D', 'E']
                              L2 = ['1', '2', '3']

                              result = dict(zip(L1, cycle(L2)))

                              print(result)


                              Output



                              {'E': '2', 'B': '2', 'A': '1', 'D': '1', 'C': '3'}


                              As an alternative you could use enumerate and index L2 modulo the length of L2:



                              result = {v: L2[i % len(L2)] for i, v in enumerate(L1)}
                              print(result)






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 9 hours ago









                              Daniel MesejoDaniel Mesejo

                              14.7k11028




                              14.7k11028























                                  9














                                  cycle is fine, but I shall add this modulo based approach:



                                  {L1[i]: L2[i % len(L2)] for i in range(len(L1))]}





                                  share|improve this answer


























                                    9














                                    cycle is fine, but I shall add this modulo based approach:



                                    {L1[i]: L2[i % len(L2)] for i in range(len(L1))]}





                                    share|improve this answer
























                                      9












                                      9








                                      9






                                      cycle is fine, but I shall add this modulo based approach:



                                      {L1[i]: L2[i % len(L2)] for i in range(len(L1))]}





                                      share|improve this answer












                                      cycle is fine, but I shall add this modulo based approach:



                                      {L1[i]: L2[i % len(L2)] for i in range(len(L1))]}






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered 9 hours ago









                                      schwobasegglschwobaseggl

                                      36.8k32441




                                      36.8k32441























                                          5














                                          You can also use a collections.deque() to create an circular FIFO queue:



                                          from collections import deque

                                          L1 = ['A', 'B', 'C', 'D', 'E']
                                          L2 = deque(['1', '2', '3'])

                                          result = {}
                                          for letter in L1:
                                          number = L2.popleft()
                                          result[letter] = number
                                          L2.append(number)

                                          print(result)
                                          # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}


                                          Which pops the left most item currently in L2 and appends it to the end once the number is added to the dictionary.



                                          Note: Both collections.deque.popleft() and collections.deque.append() are O(1) operations, so the above is still O(N), since you need to traverse all the elements in L1.






                                          share|improve this answer




























                                            5














                                            You can also use a collections.deque() to create an circular FIFO queue:



                                            from collections import deque

                                            L1 = ['A', 'B', 'C', 'D', 'E']
                                            L2 = deque(['1', '2', '3'])

                                            result = {}
                                            for letter in L1:
                                            number = L2.popleft()
                                            result[letter] = number
                                            L2.append(number)

                                            print(result)
                                            # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}


                                            Which pops the left most item currently in L2 and appends it to the end once the number is added to the dictionary.



                                            Note: Both collections.deque.popleft() and collections.deque.append() are O(1) operations, so the above is still O(N), since you need to traverse all the elements in L1.






                                            share|improve this answer


























                                              5












                                              5








                                              5






                                              You can also use a collections.deque() to create an circular FIFO queue:



                                              from collections import deque

                                              L1 = ['A', 'B', 'C', 'D', 'E']
                                              L2 = deque(['1', '2', '3'])

                                              result = {}
                                              for letter in L1:
                                              number = L2.popleft()
                                              result[letter] = number
                                              L2.append(number)

                                              print(result)
                                              # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}


                                              Which pops the left most item currently in L2 and appends it to the end once the number is added to the dictionary.



                                              Note: Both collections.deque.popleft() and collections.deque.append() are O(1) operations, so the above is still O(N), since you need to traverse all the elements in L1.






                                              share|improve this answer














                                              You can also use a collections.deque() to create an circular FIFO queue:



                                              from collections import deque

                                              L1 = ['A', 'B', 'C', 'D', 'E']
                                              L2 = deque(['1', '2', '3'])

                                              result = {}
                                              for letter in L1:
                                              number = L2.popleft()
                                              result[letter] = number
                                              L2.append(number)

                                              print(result)
                                              # {'A': '1', 'B': '2', 'C': '3', 'D': '1', 'E': '2'}


                                              Which pops the left most item currently in L2 and appends it to the end once the number is added to the dictionary.



                                              Note: Both collections.deque.popleft() and collections.deque.append() are O(1) operations, so the above is still O(N), since you need to traverse all the elements in L1.







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited 8 hours ago

























                                              answered 8 hours ago









                                              RoadRunnerRoadRunner

                                              10.9k31340




                                              10.9k31340






















                                                  Mat is a new contributor. Be nice, and check out our Code of Conduct.










                                                  draft saved

                                                  draft discarded


















                                                  Mat is a new contributor. Be nice, and check out our Code of Conduct.













                                                  Mat is a new contributor. Be nice, and check out our Code of Conduct.












                                                  Mat is a new contributor. Be nice, and check out our Code of Conduct.
















                                                  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%2f54095758%2fcreate-a-dictionary-by-zipping-together-two-lists-of-uneven-length%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

                                                  Lallio

                                                  Futebolista

                                                  Jornalista