Associating two item in a list

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
7
down vote

favorite












I am comparing two lists for common strings and my code currently works to output items in common from two lists.



list1



['5', 'orange', '20', 'apple', '50', 'blender']


list2



['25', 'blender', '20', 'pear', '40', 'spatula']


Here is my code so far:



for item1 in list1[1::2]:
for item2 in list2[1::2]:
if item1 == item2:
print(item1)


This code would return blender. What I want to do now is to also print the number before the blender in each list to obtain an output similar to:



blender, 50, 25


I have tried to add two new lines to the for loop but did not have the desired output:



for item1 in list1[1::2]:
for item2 in list2[1::2]:
for num1 in list1[0::2]:
for num2 in list2[0::2]:
if item1 == item2:
print(item1, num1, num2)


I know now that making for loops is not the answer. Also trying to call item1[-1] does not work. I am new to Python and need some help with this!



Thank you










share|improve this question

















  • 6




    This seems like an XY problem. If that is the kind of output you're looking to get, storing information in lists like that is not going to be the best approach. It honestly looks like you want a dictionary with words as keys, and the number before them as values
    – user3483203
    44 mins ago











  • Take a look at the enumerate and zip functions
    – JETM
    42 mins ago










  • Is this your special requirement to iterate over list on indexes 1,3,5.... Not on 0,2,4,6..... Consider if blender comes at index either 0,2,4,6... of any one List then will it not be considered as common element on lists??
    – Shivam Seth
    35 mins ago















up vote
7
down vote

favorite












I am comparing two lists for common strings and my code currently works to output items in common from two lists.



list1



['5', 'orange', '20', 'apple', '50', 'blender']


list2



['25', 'blender', '20', 'pear', '40', 'spatula']


Here is my code so far:



for item1 in list1[1::2]:
for item2 in list2[1::2]:
if item1 == item2:
print(item1)


This code would return blender. What I want to do now is to also print the number before the blender in each list to obtain an output similar to:



blender, 50, 25


I have tried to add two new lines to the for loop but did not have the desired output:



for item1 in list1[1::2]:
for item2 in list2[1::2]:
for num1 in list1[0::2]:
for num2 in list2[0::2]:
if item1 == item2:
print(item1, num1, num2)


I know now that making for loops is not the answer. Also trying to call item1[-1] does not work. I am new to Python and need some help with this!



Thank you










share|improve this question

















  • 6




    This seems like an XY problem. If that is the kind of output you're looking to get, storing information in lists like that is not going to be the best approach. It honestly looks like you want a dictionary with words as keys, and the number before them as values
    – user3483203
    44 mins ago











  • Take a look at the enumerate and zip functions
    – JETM
    42 mins ago










  • Is this your special requirement to iterate over list on indexes 1,3,5.... Not on 0,2,4,6..... Consider if blender comes at index either 0,2,4,6... of any one List then will it not be considered as common element on lists??
    – Shivam Seth
    35 mins ago













up vote
7
down vote

favorite









up vote
7
down vote

favorite











I am comparing two lists for common strings and my code currently works to output items in common from two lists.



list1



['5', 'orange', '20', 'apple', '50', 'blender']


list2



['25', 'blender', '20', 'pear', '40', 'spatula']


Here is my code so far:



for item1 in list1[1::2]:
for item2 in list2[1::2]:
if item1 == item2:
print(item1)


This code would return blender. What I want to do now is to also print the number before the blender in each list to obtain an output similar to:



blender, 50, 25


I have tried to add two new lines to the for loop but did not have the desired output:



for item1 in list1[1::2]:
for item2 in list2[1::2]:
for num1 in list1[0::2]:
for num2 in list2[0::2]:
if item1 == item2:
print(item1, num1, num2)


I know now that making for loops is not the answer. Also trying to call item1[-1] does not work. I am new to Python and need some help with this!



Thank you










share|improve this question













I am comparing two lists for common strings and my code currently works to output items in common from two lists.



list1



['5', 'orange', '20', 'apple', '50', 'blender']


list2



['25', 'blender', '20', 'pear', '40', 'spatula']


Here is my code so far:



for item1 in list1[1::2]:
for item2 in list2[1::2]:
if item1 == item2:
print(item1)


This code would return blender. What I want to do now is to also print the number before the blender in each list to obtain an output similar to:



blender, 50, 25


I have tried to add two new lines to the for loop but did not have the desired output:



for item1 in list1[1::2]:
for item2 in list2[1::2]:
for num1 in list1[0::2]:
for num2 in list2[0::2]:
if item1 == item2:
print(item1, num1, num2)


I know now that making for loops is not the answer. Also trying to call item1[-1] does not work. I am new to Python and need some help with this!



Thank you







python list






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 45 mins ago









stevesy

383




383







  • 6




    This seems like an XY problem. If that is the kind of output you're looking to get, storing information in lists like that is not going to be the best approach. It honestly looks like you want a dictionary with words as keys, and the number before them as values
    – user3483203
    44 mins ago











  • Take a look at the enumerate and zip functions
    – JETM
    42 mins ago










  • Is this your special requirement to iterate over list on indexes 1,3,5.... Not on 0,2,4,6..... Consider if blender comes at index either 0,2,4,6... of any one List then will it not be considered as common element on lists??
    – Shivam Seth
    35 mins ago













  • 6




    This seems like an XY problem. If that is the kind of output you're looking to get, storing information in lists like that is not going to be the best approach. It honestly looks like you want a dictionary with words as keys, and the number before them as values
    – user3483203
    44 mins ago











  • Take a look at the enumerate and zip functions
    – JETM
    42 mins ago










  • Is this your special requirement to iterate over list on indexes 1,3,5.... Not on 0,2,4,6..... Consider if blender comes at index either 0,2,4,6... of any one List then will it not be considered as common element on lists??
    – Shivam Seth
    35 mins ago








6




6




This seems like an XY problem. If that is the kind of output you're looking to get, storing information in lists like that is not going to be the best approach. It honestly looks like you want a dictionary with words as keys, and the number before them as values
– user3483203
44 mins ago





This seems like an XY problem. If that is the kind of output you're looking to get, storing information in lists like that is not going to be the best approach. It honestly looks like you want a dictionary with words as keys, and the number before them as values
– user3483203
44 mins ago













Take a look at the enumerate and zip functions
– JETM
42 mins ago




Take a look at the enumerate and zip functions
– JETM
42 mins ago












Is this your special requirement to iterate over list on indexes 1,3,5.... Not on 0,2,4,6..... Consider if blender comes at index either 0,2,4,6... of any one List then will it not be considered as common element on lists??
– Shivam Seth
35 mins ago





Is this your special requirement to iterate over list on indexes 1,3,5.... Not on 0,2,4,6..... Consider if blender comes at index either 0,2,4,6... of any one List then will it not be considered as common element on lists??
– Shivam Seth
35 mins ago













6 Answers
6






active

oldest

votes

















up vote
5
down vote



accepted










You can do it in two ways, either stay with lists (Which is more messy):



list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
for item1 in list1[1::2]:
for item2 in list2[1::2]:
if item1 == item2:
item_to_print = item1
print(item1, ",", end="")
for index in range(len(list1)):
if list1[index] == item1:
print(list1[index - 1], ",", end="")
for index in range(len(list2)):
if list2[index] == item1:
print(list2[index - 1])


or the better way (in my opinion) with dictionary:



dict1 = 'apple': '20', 'blender': '50', 'orange': '5'
dict2 = 'blender': '25', 'pear': '20', 'spatula': '40'
for item in dict1:
if item in dict2:
print(item, ",", dict1[item], ",", dict2[item])


Both will output:



>> blender , 50 , 25





share|improve this answer




















  • Thank you, I ended up using this and it works great!
    – stevesy
    28 mins ago






  • 1




    @stevesy Your'e welcome mate.
    – MercyDude
    21 mins ago

















up vote
4
down vote













I think you'd be better suited using dictionaries for this problem..



dict1 = 'orange': 5, 'apple': 20, 'blender': 50
dict2 = 'blender': 25, 'pear': 20, 'spatula': 40


so to get the outputs you want



>>dict1['blender']
50
>>dict2['blender']
25


So if you want to get the number of blenders from each dictionary in the format you want, you can really just use



print("blender, "+str(dict1['blender'])+", "+str(dict2['blender']))


To take this one step further and output based on what's in dict1 and dict2



for i in dict1.keys(): #dict1.keys() is essentially a list with ['orange','apple','blender']
if i in dict2.keys(): #same deal, but different items in the list
print(str(i)+", "+str(dict1[i])+", "+str(dict2[i])) #this outputs items that are in BOTH lists
else:
print(str(i)+", "+str(dict1[i])) #this outputs items ONLY in dict1
for i in dict2.keys():
if i not in dict1.keys(): #we use not since we already output the matching in the previous loop
print(str(i)+", "+str(dict2[i])) #this outputs items ONLY in dict2


Outputs:



orange, 5
apple, 20
blender, 50, 25
pear, 20
spatula, 40





share|improve this answer





























    up vote
    3
    down vote













    You're approaching this problem with the wrong Data Structure. You shouldn't keep this data in lists if you're doing lookups between the two. Instead, it would be much easier to use a dictionary here.



    Setup



    You can use zip to create these two dictionaries:



    a = ['5', 'orange', '20', 'apple', '50', 'blender']
    b = ['25', 'blender', '20', 'pear', '40', 'spatula']

    dct_a = dict(zip(a[1::2], a[::2]))
    dct_b = dict(zip(b[1::2], b[::2]))


    This will leave you with these two dictionaries:



    'orange': '5', 'apple': '20', 'blender': '50'
    'blender': '25', 'pear': '20', 'spatula': '40'



    This makes every part of your problem easier to solve. For example, to find common keys:



    common = dct_a.keys() & dct_b.keys()
    # 'blender'


    And to find all the values matching each common key:



    [(k, dct_a[k], dct_b[k]) for k in common]


    Output:



    [('blender', '50', '25')]





    share|improve this answer




















    • Thank you, I haven't gone over dictionaries yet in my class but this does work!
      – stevesy
      27 mins ago

















    up vote
    3
    down vote













    with enumerate you can solve your problem:



    list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
    list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']



    for n1, item1 in enumerate(list1[1::2]):
    for n2, item2 in enumerate(list2[1::2]):
    if item1 == item2:
    print(list1[n1*2], list2[n2*2], item1)


    enumerate returns a tuple where the first element is the count of the iteration, the second the element.

    Since enumerate is counting the iteration and you're stepping 2, we need to multiply by 2:
    orange will be the first iteration, so n1 will be 0, so the previous value is at index 0*2
    apple will be in the second iteration, so n1 will be 1, so the previous value is at index 1*2
    blender will be in the third iteration, so n1 will be 2, so the previousl value is at index 2*2.



    this means that in for n1, item1 in enumerate(list1[1::2]): n1 and item1 will have this values:




    Iteration 1: n1 = 0, item1 = orange, previous_index = 0*2

    Iteration 2: n1 = 1, item1 = apple, previous_index = 1*2

    Iteration 3: n1 = 2, item1 = blender, previous_index = 2*2




    same goes for for n2, item2 in enumerate(list2[1::2])::




    Iteration 1: n2 = 0, item2 = blender, previous_index = 0*2

    Iteration 2: n2 = 1, item2 = pear, previous_index = 1*2

    Iteration 3: n2 = 2, item2 = spatula, previous_index = 2*2







    share|improve this answer






















    • This is great, I have to read up on the enumerate function some more but this worked!
      – stevesy
      28 mins ago

















    up vote
    3
    down vote













    Assuming the nouns in your lists are unique (per list), create dictionaries out of your lists first.



    In [1]: list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
    In [2]: list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
    In [3]:
    In [3]: dict1 = dict(reversed(pair) for pair in zip(*[iter(list1)]*2))
    In [4]: dict2 = dict(reversed(pair) for pair in zip(*[iter(list2)]*2))
    In [5]:
    In [5]: dict1
    Out[5]: 'apple': '20', 'blender': '50', 'orange': '5'
    In [6]: dict2
    Out[6]: 'blender': '25', 'pear': '20', 'spatula': '40'


    This code leverages the grouper recipe from the itertools docs.



    Matching two items from your dictionaries is easy as pie.



    In [7]: key = 'blender'
    In [8]: print(key, dict1[key], dict2[key])
    blender 50 25


    You could even build a dictionary that holds the common keys from dict1 and dict2 and a list of the values.



    In [12]: common = dict1.keys() & dict2
    In [13]: c:[dict1[c], dict2[c]] for c in common
    Out[13]: 'blender': ['50', '25']


    For an arbitrary number of dicts, you can abstract this further.



    In [28]: from functools import reduce
    In [29]: from operator import and_
    In [30]:
    In [30]: dicts = (dict1, dict2)
    In [31]: common = reduce(and_, map(set, dicts))
    In [32]: c:[d[c] for d in dicts] for c in common
    Out[32]: 'blender': ['50', '25']





    share|improve this answer






















    • I wrote a similar variant pastebin.com/MgiLJzZf
      – Chris_Rands
      37 mins ago

















    up vote
    2
    down vote













    I hope this code will work for you.



    l1 =['5', 'orange', '20', 'apple', '50', 'blender']
    l2 = ['25', 'blender', '20', 'pear', '40', 'spatula']

    for list1_item in zip(*[iter(l1)]*2):
    for list2_item in zip(*[iter(l2)]*2):
    if list1_item[1]==list2_item[1]:
    print list1_item[1],list1_item[0],list2_item[0]


    it will print output



    blender 50 25





    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: false,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      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%2f52390125%2fassociating-two-item-in-a-list%23new-answer', 'question_page');

      );

      Post as a guest






























      6 Answers
      6






      active

      oldest

      votes








      6 Answers
      6






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      5
      down vote



      accepted










      You can do it in two ways, either stay with lists (Which is more messy):



      list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
      list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
      for item1 in list1[1::2]:
      for item2 in list2[1::2]:
      if item1 == item2:
      item_to_print = item1
      print(item1, ",", end="")
      for index in range(len(list1)):
      if list1[index] == item1:
      print(list1[index - 1], ",", end="")
      for index in range(len(list2)):
      if list2[index] == item1:
      print(list2[index - 1])


      or the better way (in my opinion) with dictionary:



      dict1 = 'apple': '20', 'blender': '50', 'orange': '5'
      dict2 = 'blender': '25', 'pear': '20', 'spatula': '40'
      for item in dict1:
      if item in dict2:
      print(item, ",", dict1[item], ",", dict2[item])


      Both will output:



      >> blender , 50 , 25





      share|improve this answer




















      • Thank you, I ended up using this and it works great!
        – stevesy
        28 mins ago






      • 1




        @stevesy Your'e welcome mate.
        – MercyDude
        21 mins ago














      up vote
      5
      down vote



      accepted










      You can do it in two ways, either stay with lists (Which is more messy):



      list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
      list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
      for item1 in list1[1::2]:
      for item2 in list2[1::2]:
      if item1 == item2:
      item_to_print = item1
      print(item1, ",", end="")
      for index in range(len(list1)):
      if list1[index] == item1:
      print(list1[index - 1], ",", end="")
      for index in range(len(list2)):
      if list2[index] == item1:
      print(list2[index - 1])


      or the better way (in my opinion) with dictionary:



      dict1 = 'apple': '20', 'blender': '50', 'orange': '5'
      dict2 = 'blender': '25', 'pear': '20', 'spatula': '40'
      for item in dict1:
      if item in dict2:
      print(item, ",", dict1[item], ",", dict2[item])


      Both will output:



      >> blender , 50 , 25





      share|improve this answer




















      • Thank you, I ended up using this and it works great!
        – stevesy
        28 mins ago






      • 1




        @stevesy Your'e welcome mate.
        – MercyDude
        21 mins ago












      up vote
      5
      down vote



      accepted







      up vote
      5
      down vote



      accepted






      You can do it in two ways, either stay with lists (Which is more messy):



      list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
      list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
      for item1 in list1[1::2]:
      for item2 in list2[1::2]:
      if item1 == item2:
      item_to_print = item1
      print(item1, ",", end="")
      for index in range(len(list1)):
      if list1[index] == item1:
      print(list1[index - 1], ",", end="")
      for index in range(len(list2)):
      if list2[index] == item1:
      print(list2[index - 1])


      or the better way (in my opinion) with dictionary:



      dict1 = 'apple': '20', 'blender': '50', 'orange': '5'
      dict2 = 'blender': '25', 'pear': '20', 'spatula': '40'
      for item in dict1:
      if item in dict2:
      print(item, ",", dict1[item], ",", dict2[item])


      Both will output:



      >> blender , 50 , 25





      share|improve this answer












      You can do it in two ways, either stay with lists (Which is more messy):



      list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
      list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
      for item1 in list1[1::2]:
      for item2 in list2[1::2]:
      if item1 == item2:
      item_to_print = item1
      print(item1, ",", end="")
      for index in range(len(list1)):
      if list1[index] == item1:
      print(list1[index - 1], ",", end="")
      for index in range(len(list2)):
      if list2[index] == item1:
      print(list2[index - 1])


      or the better way (in my opinion) with dictionary:



      dict1 = 'apple': '20', 'blender': '50', 'orange': '5'
      dict2 = 'blender': '25', 'pear': '20', 'spatula': '40'
      for item in dict1:
      if item in dict2:
      print(item, ",", dict1[item], ",", dict2[item])


      Both will output:



      >> blender , 50 , 25






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered 33 mins ago









      MercyDude

      376418




      376418











      • Thank you, I ended up using this and it works great!
        – stevesy
        28 mins ago






      • 1




        @stevesy Your'e welcome mate.
        – MercyDude
        21 mins ago
















      • Thank you, I ended up using this and it works great!
        – stevesy
        28 mins ago






      • 1




        @stevesy Your'e welcome mate.
        – MercyDude
        21 mins ago















      Thank you, I ended up using this and it works great!
      – stevesy
      28 mins ago




      Thank you, I ended up using this and it works great!
      – stevesy
      28 mins ago




      1




      1




      @stevesy Your'e welcome mate.
      – MercyDude
      21 mins ago




      @stevesy Your'e welcome mate.
      – MercyDude
      21 mins ago












      up vote
      4
      down vote













      I think you'd be better suited using dictionaries for this problem..



      dict1 = 'orange': 5, 'apple': 20, 'blender': 50
      dict2 = 'blender': 25, 'pear': 20, 'spatula': 40


      so to get the outputs you want



      >>dict1['blender']
      50
      >>dict2['blender']
      25


      So if you want to get the number of blenders from each dictionary in the format you want, you can really just use



      print("blender, "+str(dict1['blender'])+", "+str(dict2['blender']))


      To take this one step further and output based on what's in dict1 and dict2



      for i in dict1.keys(): #dict1.keys() is essentially a list with ['orange','apple','blender']
      if i in dict2.keys(): #same deal, but different items in the list
      print(str(i)+", "+str(dict1[i])+", "+str(dict2[i])) #this outputs items that are in BOTH lists
      else:
      print(str(i)+", "+str(dict1[i])) #this outputs items ONLY in dict1
      for i in dict2.keys():
      if i not in dict1.keys(): #we use not since we already output the matching in the previous loop
      print(str(i)+", "+str(dict2[i])) #this outputs items ONLY in dict2


      Outputs:



      orange, 5
      apple, 20
      blender, 50, 25
      pear, 20
      spatula, 40





      share|improve this answer


























        up vote
        4
        down vote













        I think you'd be better suited using dictionaries for this problem..



        dict1 = 'orange': 5, 'apple': 20, 'blender': 50
        dict2 = 'blender': 25, 'pear': 20, 'spatula': 40


        so to get the outputs you want



        >>dict1['blender']
        50
        >>dict2['blender']
        25


        So if you want to get the number of blenders from each dictionary in the format you want, you can really just use



        print("blender, "+str(dict1['blender'])+", "+str(dict2['blender']))


        To take this one step further and output based on what's in dict1 and dict2



        for i in dict1.keys(): #dict1.keys() is essentially a list with ['orange','apple','blender']
        if i in dict2.keys(): #same deal, but different items in the list
        print(str(i)+", "+str(dict1[i])+", "+str(dict2[i])) #this outputs items that are in BOTH lists
        else:
        print(str(i)+", "+str(dict1[i])) #this outputs items ONLY in dict1
        for i in dict2.keys():
        if i not in dict1.keys(): #we use not since we already output the matching in the previous loop
        print(str(i)+", "+str(dict2[i])) #this outputs items ONLY in dict2


        Outputs:



        orange, 5
        apple, 20
        blender, 50, 25
        pear, 20
        spatula, 40





        share|improve this answer
























          up vote
          4
          down vote










          up vote
          4
          down vote









          I think you'd be better suited using dictionaries for this problem..



          dict1 = 'orange': 5, 'apple': 20, 'blender': 50
          dict2 = 'blender': 25, 'pear': 20, 'spatula': 40


          so to get the outputs you want



          >>dict1['blender']
          50
          >>dict2['blender']
          25


          So if you want to get the number of blenders from each dictionary in the format you want, you can really just use



          print("blender, "+str(dict1['blender'])+", "+str(dict2['blender']))


          To take this one step further and output based on what's in dict1 and dict2



          for i in dict1.keys(): #dict1.keys() is essentially a list with ['orange','apple','blender']
          if i in dict2.keys(): #same deal, but different items in the list
          print(str(i)+", "+str(dict1[i])+", "+str(dict2[i])) #this outputs items that are in BOTH lists
          else:
          print(str(i)+", "+str(dict1[i])) #this outputs items ONLY in dict1
          for i in dict2.keys():
          if i not in dict1.keys(): #we use not since we already output the matching in the previous loop
          print(str(i)+", "+str(dict2[i])) #this outputs items ONLY in dict2


          Outputs:



          orange, 5
          apple, 20
          blender, 50, 25
          pear, 20
          spatula, 40





          share|improve this answer














          I think you'd be better suited using dictionaries for this problem..



          dict1 = 'orange': 5, 'apple': 20, 'blender': 50
          dict2 = 'blender': 25, 'pear': 20, 'spatula': 40


          so to get the outputs you want



          >>dict1['blender']
          50
          >>dict2['blender']
          25


          So if you want to get the number of blenders from each dictionary in the format you want, you can really just use



          print("blender, "+str(dict1['blender'])+", "+str(dict2['blender']))


          To take this one step further and output based on what's in dict1 and dict2



          for i in dict1.keys(): #dict1.keys() is essentially a list with ['orange','apple','blender']
          if i in dict2.keys(): #same deal, but different items in the list
          print(str(i)+", "+str(dict1[i])+", "+str(dict2[i])) #this outputs items that are in BOTH lists
          else:
          print(str(i)+", "+str(dict1[i])) #this outputs items ONLY in dict1
          for i in dict2.keys():
          if i not in dict1.keys(): #we use not since we already output the matching in the previous loop
          print(str(i)+", "+str(dict2[i])) #this outputs items ONLY in dict2


          Outputs:



          orange, 5
          apple, 20
          blender, 50, 25
          pear, 20
          spatula, 40






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 32 mins ago

























          answered 37 mins ago









          J0hn

          458314




          458314




















              up vote
              3
              down vote













              You're approaching this problem with the wrong Data Structure. You shouldn't keep this data in lists if you're doing lookups between the two. Instead, it would be much easier to use a dictionary here.



              Setup



              You can use zip to create these two dictionaries:



              a = ['5', 'orange', '20', 'apple', '50', 'blender']
              b = ['25', 'blender', '20', 'pear', '40', 'spatula']

              dct_a = dict(zip(a[1::2], a[::2]))
              dct_b = dict(zip(b[1::2], b[::2]))


              This will leave you with these two dictionaries:



              'orange': '5', 'apple': '20', 'blender': '50'
              'blender': '25', 'pear': '20', 'spatula': '40'



              This makes every part of your problem easier to solve. For example, to find common keys:



              common = dct_a.keys() & dct_b.keys()
              # 'blender'


              And to find all the values matching each common key:



              [(k, dct_a[k], dct_b[k]) for k in common]


              Output:



              [('blender', '50', '25')]





              share|improve this answer




















              • Thank you, I haven't gone over dictionaries yet in my class but this does work!
                – stevesy
                27 mins ago














              up vote
              3
              down vote













              You're approaching this problem with the wrong Data Structure. You shouldn't keep this data in lists if you're doing lookups between the two. Instead, it would be much easier to use a dictionary here.



              Setup



              You can use zip to create these two dictionaries:



              a = ['5', 'orange', '20', 'apple', '50', 'blender']
              b = ['25', 'blender', '20', 'pear', '40', 'spatula']

              dct_a = dict(zip(a[1::2], a[::2]))
              dct_b = dict(zip(b[1::2], b[::2]))


              This will leave you with these two dictionaries:



              'orange': '5', 'apple': '20', 'blender': '50'
              'blender': '25', 'pear': '20', 'spatula': '40'



              This makes every part of your problem easier to solve. For example, to find common keys:



              common = dct_a.keys() & dct_b.keys()
              # 'blender'


              And to find all the values matching each common key:



              [(k, dct_a[k], dct_b[k]) for k in common]


              Output:



              [('blender', '50', '25')]





              share|improve this answer




















              • Thank you, I haven't gone over dictionaries yet in my class but this does work!
                – stevesy
                27 mins ago












              up vote
              3
              down vote










              up vote
              3
              down vote









              You're approaching this problem with the wrong Data Structure. You shouldn't keep this data in lists if you're doing lookups between the two. Instead, it would be much easier to use a dictionary here.



              Setup



              You can use zip to create these two dictionaries:



              a = ['5', 'orange', '20', 'apple', '50', 'blender']
              b = ['25', 'blender', '20', 'pear', '40', 'spatula']

              dct_a = dict(zip(a[1::2], a[::2]))
              dct_b = dict(zip(b[1::2], b[::2]))


              This will leave you with these two dictionaries:



              'orange': '5', 'apple': '20', 'blender': '50'
              'blender': '25', 'pear': '20', 'spatula': '40'



              This makes every part of your problem easier to solve. For example, to find common keys:



              common = dct_a.keys() & dct_b.keys()
              # 'blender'


              And to find all the values matching each common key:



              [(k, dct_a[k], dct_b[k]) for k in common]


              Output:



              [('blender', '50', '25')]





              share|improve this answer












              You're approaching this problem with the wrong Data Structure. You shouldn't keep this data in lists if you're doing lookups between the two. Instead, it would be much easier to use a dictionary here.



              Setup



              You can use zip to create these two dictionaries:



              a = ['5', 'orange', '20', 'apple', '50', 'blender']
              b = ['25', 'blender', '20', 'pear', '40', 'spatula']

              dct_a = dict(zip(a[1::2], a[::2]))
              dct_b = dict(zip(b[1::2], b[::2]))


              This will leave you with these two dictionaries:



              'orange': '5', 'apple': '20', 'blender': '50'
              'blender': '25', 'pear': '20', 'spatula': '40'



              This makes every part of your problem easier to solve. For example, to find common keys:



              common = dct_a.keys() & dct_b.keys()
              # 'blender'


              And to find all the values matching each common key:



              [(k, dct_a[k], dct_b[k]) for k in common]


              Output:



              [('blender', '50', '25')]






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 40 mins ago









              user3483203

              24.1k62147




              24.1k62147











              • Thank you, I haven't gone over dictionaries yet in my class but this does work!
                – stevesy
                27 mins ago
















              • Thank you, I haven't gone over dictionaries yet in my class but this does work!
                – stevesy
                27 mins ago















              Thank you, I haven't gone over dictionaries yet in my class but this does work!
              – stevesy
              27 mins ago




              Thank you, I haven't gone over dictionaries yet in my class but this does work!
              – stevesy
              27 mins ago










              up vote
              3
              down vote













              with enumerate you can solve your problem:



              list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
              list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']



              for n1, item1 in enumerate(list1[1::2]):
              for n2, item2 in enumerate(list2[1::2]):
              if item1 == item2:
              print(list1[n1*2], list2[n2*2], item1)


              enumerate returns a tuple where the first element is the count of the iteration, the second the element.

              Since enumerate is counting the iteration and you're stepping 2, we need to multiply by 2:
              orange will be the first iteration, so n1 will be 0, so the previous value is at index 0*2
              apple will be in the second iteration, so n1 will be 1, so the previous value is at index 1*2
              blender will be in the third iteration, so n1 will be 2, so the previousl value is at index 2*2.



              this means that in for n1, item1 in enumerate(list1[1::2]): n1 and item1 will have this values:




              Iteration 1: n1 = 0, item1 = orange, previous_index = 0*2

              Iteration 2: n1 = 1, item1 = apple, previous_index = 1*2

              Iteration 3: n1 = 2, item1 = blender, previous_index = 2*2




              same goes for for n2, item2 in enumerate(list2[1::2])::




              Iteration 1: n2 = 0, item2 = blender, previous_index = 0*2

              Iteration 2: n2 = 1, item2 = pear, previous_index = 1*2

              Iteration 3: n2 = 2, item2 = spatula, previous_index = 2*2







              share|improve this answer






















              • This is great, I have to read up on the enumerate function some more but this worked!
                – stevesy
                28 mins ago














              up vote
              3
              down vote













              with enumerate you can solve your problem:



              list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
              list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']



              for n1, item1 in enumerate(list1[1::2]):
              for n2, item2 in enumerate(list2[1::2]):
              if item1 == item2:
              print(list1[n1*2], list2[n2*2], item1)


              enumerate returns a tuple where the first element is the count of the iteration, the second the element.

              Since enumerate is counting the iteration and you're stepping 2, we need to multiply by 2:
              orange will be the first iteration, so n1 will be 0, so the previous value is at index 0*2
              apple will be in the second iteration, so n1 will be 1, so the previous value is at index 1*2
              blender will be in the third iteration, so n1 will be 2, so the previousl value is at index 2*2.



              this means that in for n1, item1 in enumerate(list1[1::2]): n1 and item1 will have this values:




              Iteration 1: n1 = 0, item1 = orange, previous_index = 0*2

              Iteration 2: n1 = 1, item1 = apple, previous_index = 1*2

              Iteration 3: n1 = 2, item1 = blender, previous_index = 2*2




              same goes for for n2, item2 in enumerate(list2[1::2])::




              Iteration 1: n2 = 0, item2 = blender, previous_index = 0*2

              Iteration 2: n2 = 1, item2 = pear, previous_index = 1*2

              Iteration 3: n2 = 2, item2 = spatula, previous_index = 2*2







              share|improve this answer






















              • This is great, I have to read up on the enumerate function some more but this worked!
                – stevesy
                28 mins ago












              up vote
              3
              down vote










              up vote
              3
              down vote









              with enumerate you can solve your problem:



              list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
              list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']



              for n1, item1 in enumerate(list1[1::2]):
              for n2, item2 in enumerate(list2[1::2]):
              if item1 == item2:
              print(list1[n1*2], list2[n2*2], item1)


              enumerate returns a tuple where the first element is the count of the iteration, the second the element.

              Since enumerate is counting the iteration and you're stepping 2, we need to multiply by 2:
              orange will be the first iteration, so n1 will be 0, so the previous value is at index 0*2
              apple will be in the second iteration, so n1 will be 1, so the previous value is at index 1*2
              blender will be in the third iteration, so n1 will be 2, so the previousl value is at index 2*2.



              this means that in for n1, item1 in enumerate(list1[1::2]): n1 and item1 will have this values:




              Iteration 1: n1 = 0, item1 = orange, previous_index = 0*2

              Iteration 2: n1 = 1, item1 = apple, previous_index = 1*2

              Iteration 3: n1 = 2, item1 = blender, previous_index = 2*2




              same goes for for n2, item2 in enumerate(list2[1::2])::




              Iteration 1: n2 = 0, item2 = blender, previous_index = 0*2

              Iteration 2: n2 = 1, item2 = pear, previous_index = 1*2

              Iteration 3: n2 = 2, item2 = spatula, previous_index = 2*2







              share|improve this answer














              with enumerate you can solve your problem:



              list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
              list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']



              for n1, item1 in enumerate(list1[1::2]):
              for n2, item2 in enumerate(list2[1::2]):
              if item1 == item2:
              print(list1[n1*2], list2[n2*2], item1)


              enumerate returns a tuple where the first element is the count of the iteration, the second the element.

              Since enumerate is counting the iteration and you're stepping 2, we need to multiply by 2:
              orange will be the first iteration, so n1 will be 0, so the previous value is at index 0*2
              apple will be in the second iteration, so n1 will be 1, so the previous value is at index 1*2
              blender will be in the third iteration, so n1 will be 2, so the previousl value is at index 2*2.



              this means that in for n1, item1 in enumerate(list1[1::2]): n1 and item1 will have this values:




              Iteration 1: n1 = 0, item1 = orange, previous_index = 0*2

              Iteration 2: n1 = 1, item1 = apple, previous_index = 1*2

              Iteration 3: n1 = 2, item1 = blender, previous_index = 2*2




              same goes for for n2, item2 in enumerate(list2[1::2])::




              Iteration 1: n2 = 0, item2 = blender, previous_index = 0*2

              Iteration 2: n2 = 1, item2 = pear, previous_index = 1*2

              Iteration 3: n2 = 2, item2 = spatula, previous_index = 2*2








              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 25 mins ago

























              answered 36 mins ago









              Gsk

              1,76511216




              1,76511216











              • This is great, I have to read up on the enumerate function some more but this worked!
                – stevesy
                28 mins ago
















              • This is great, I have to read up on the enumerate function some more but this worked!
                – stevesy
                28 mins ago















              This is great, I have to read up on the enumerate function some more but this worked!
              – stevesy
              28 mins ago




              This is great, I have to read up on the enumerate function some more but this worked!
              – stevesy
              28 mins ago










              up vote
              3
              down vote













              Assuming the nouns in your lists are unique (per list), create dictionaries out of your lists first.



              In [1]: list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
              In [2]: list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
              In [3]:
              In [3]: dict1 = dict(reversed(pair) for pair in zip(*[iter(list1)]*2))
              In [4]: dict2 = dict(reversed(pair) for pair in zip(*[iter(list2)]*2))
              In [5]:
              In [5]: dict1
              Out[5]: 'apple': '20', 'blender': '50', 'orange': '5'
              In [6]: dict2
              Out[6]: 'blender': '25', 'pear': '20', 'spatula': '40'


              This code leverages the grouper recipe from the itertools docs.



              Matching two items from your dictionaries is easy as pie.



              In [7]: key = 'blender'
              In [8]: print(key, dict1[key], dict2[key])
              blender 50 25


              You could even build a dictionary that holds the common keys from dict1 and dict2 and a list of the values.



              In [12]: common = dict1.keys() & dict2
              In [13]: c:[dict1[c], dict2[c]] for c in common
              Out[13]: 'blender': ['50', '25']


              For an arbitrary number of dicts, you can abstract this further.



              In [28]: from functools import reduce
              In [29]: from operator import and_
              In [30]:
              In [30]: dicts = (dict1, dict2)
              In [31]: common = reduce(and_, map(set, dicts))
              In [32]: c:[d[c] for d in dicts] for c in common
              Out[32]: 'blender': ['50', '25']





              share|improve this answer






















              • I wrote a similar variant pastebin.com/MgiLJzZf
                – Chris_Rands
                37 mins ago














              up vote
              3
              down vote













              Assuming the nouns in your lists are unique (per list), create dictionaries out of your lists first.



              In [1]: list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
              In [2]: list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
              In [3]:
              In [3]: dict1 = dict(reversed(pair) for pair in zip(*[iter(list1)]*2))
              In [4]: dict2 = dict(reversed(pair) for pair in zip(*[iter(list2)]*2))
              In [5]:
              In [5]: dict1
              Out[5]: 'apple': '20', 'blender': '50', 'orange': '5'
              In [6]: dict2
              Out[6]: 'blender': '25', 'pear': '20', 'spatula': '40'


              This code leverages the grouper recipe from the itertools docs.



              Matching two items from your dictionaries is easy as pie.



              In [7]: key = 'blender'
              In [8]: print(key, dict1[key], dict2[key])
              blender 50 25


              You could even build a dictionary that holds the common keys from dict1 and dict2 and a list of the values.



              In [12]: common = dict1.keys() & dict2
              In [13]: c:[dict1[c], dict2[c]] for c in common
              Out[13]: 'blender': ['50', '25']


              For an arbitrary number of dicts, you can abstract this further.



              In [28]: from functools import reduce
              In [29]: from operator import and_
              In [30]:
              In [30]: dicts = (dict1, dict2)
              In [31]: common = reduce(and_, map(set, dicts))
              In [32]: c:[d[c] for d in dicts] for c in common
              Out[32]: 'blender': ['50', '25']





              share|improve this answer






















              • I wrote a similar variant pastebin.com/MgiLJzZf
                – Chris_Rands
                37 mins ago












              up vote
              3
              down vote










              up vote
              3
              down vote









              Assuming the nouns in your lists are unique (per list), create dictionaries out of your lists first.



              In [1]: list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
              In [2]: list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
              In [3]:
              In [3]: dict1 = dict(reversed(pair) for pair in zip(*[iter(list1)]*2))
              In [4]: dict2 = dict(reversed(pair) for pair in zip(*[iter(list2)]*2))
              In [5]:
              In [5]: dict1
              Out[5]: 'apple': '20', 'blender': '50', 'orange': '5'
              In [6]: dict2
              Out[6]: 'blender': '25', 'pear': '20', 'spatula': '40'


              This code leverages the grouper recipe from the itertools docs.



              Matching two items from your dictionaries is easy as pie.



              In [7]: key = 'blender'
              In [8]: print(key, dict1[key], dict2[key])
              blender 50 25


              You could even build a dictionary that holds the common keys from dict1 and dict2 and a list of the values.



              In [12]: common = dict1.keys() & dict2
              In [13]: c:[dict1[c], dict2[c]] for c in common
              Out[13]: 'blender': ['50', '25']


              For an arbitrary number of dicts, you can abstract this further.



              In [28]: from functools import reduce
              In [29]: from operator import and_
              In [30]:
              In [30]: dicts = (dict1, dict2)
              In [31]: common = reduce(and_, map(set, dicts))
              In [32]: c:[d[c] for d in dicts] for c in common
              Out[32]: 'blender': ['50', '25']





              share|improve this answer














              Assuming the nouns in your lists are unique (per list), create dictionaries out of your lists first.



              In [1]: list1 = ['5', 'orange', '20', 'apple', '50', 'blender']
              In [2]: list2 = ['25', 'blender', '20', 'pear', '40', 'spatula']
              In [3]:
              In [3]: dict1 = dict(reversed(pair) for pair in zip(*[iter(list1)]*2))
              In [4]: dict2 = dict(reversed(pair) for pair in zip(*[iter(list2)]*2))
              In [5]:
              In [5]: dict1
              Out[5]: 'apple': '20', 'blender': '50', 'orange': '5'
              In [6]: dict2
              Out[6]: 'blender': '25', 'pear': '20', 'spatula': '40'


              This code leverages the grouper recipe from the itertools docs.



              Matching two items from your dictionaries is easy as pie.



              In [7]: key = 'blender'
              In [8]: print(key, dict1[key], dict2[key])
              blender 50 25


              You could even build a dictionary that holds the common keys from dict1 and dict2 and a list of the values.



              In [12]: common = dict1.keys() & dict2
              In [13]: c:[dict1[c], dict2[c]] for c in common
              Out[13]: 'blender': ['50', '25']


              For an arbitrary number of dicts, you can abstract this further.



              In [28]: from functools import reduce
              In [29]: from operator import and_
              In [30]:
              In [30]: dicts = (dict1, dict2)
              In [31]: common = reduce(and_, map(set, dicts))
              In [32]: c:[d[c] for d in dicts] for c in common
              Out[32]: 'blender': ['50', '25']






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 24 mins ago

























              answered 40 mins ago









              timgeb

              36.9k104875




              36.9k104875











              • I wrote a similar variant pastebin.com/MgiLJzZf
                – Chris_Rands
                37 mins ago
















              • I wrote a similar variant pastebin.com/MgiLJzZf
                – Chris_Rands
                37 mins ago















              I wrote a similar variant pastebin.com/MgiLJzZf
              – Chris_Rands
              37 mins ago




              I wrote a similar variant pastebin.com/MgiLJzZf
              – Chris_Rands
              37 mins ago










              up vote
              2
              down vote













              I hope this code will work for you.



              l1 =['5', 'orange', '20', 'apple', '50', 'blender']
              l2 = ['25', 'blender', '20', 'pear', '40', 'spatula']

              for list1_item in zip(*[iter(l1)]*2):
              for list2_item in zip(*[iter(l2)]*2):
              if list1_item[1]==list2_item[1]:
              print list1_item[1],list1_item[0],list2_item[0]


              it will print output



              blender 50 25





              share|improve this answer
























                up vote
                2
                down vote













                I hope this code will work for you.



                l1 =['5', 'orange', '20', 'apple', '50', 'blender']
                l2 = ['25', 'blender', '20', 'pear', '40', 'spatula']

                for list1_item in zip(*[iter(l1)]*2):
                for list2_item in zip(*[iter(l2)]*2):
                if list1_item[1]==list2_item[1]:
                print list1_item[1],list1_item[0],list2_item[0]


                it will print output



                blender 50 25





                share|improve this answer






















                  up vote
                  2
                  down vote










                  up vote
                  2
                  down vote









                  I hope this code will work for you.



                  l1 =['5', 'orange', '20', 'apple', '50', 'blender']
                  l2 = ['25', 'blender', '20', 'pear', '40', 'spatula']

                  for list1_item in zip(*[iter(l1)]*2):
                  for list2_item in zip(*[iter(l2)]*2):
                  if list1_item[1]==list2_item[1]:
                  print list1_item[1],list1_item[0],list2_item[0]


                  it will print output



                  blender 50 25





                  share|improve this answer












                  I hope this code will work for you.



                  l1 =['5', 'orange', '20', 'apple', '50', 'blender']
                  l2 = ['25', 'blender', '20', 'pear', '40', 'spatula']

                  for list1_item in zip(*[iter(l1)]*2):
                  for list2_item in zip(*[iter(l2)]*2):
                  if list1_item[1]==list2_item[1]:
                  print list1_item[1],list1_item[0],list2_item[0]


                  it will print output



                  blender 50 25






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 29 mins ago









                  Abdul Majeed

                  1,5211315




                  1,5211315



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52390125%2fassociating-two-item-in-a-list%23new-answer', 'question_page');

                      );

                      Post as a guest













































































                      Comments

                      Popular posts from this blog

                      What does second last employer means? [closed]

                      Installing NextGIS Connect into QGIS 3?

                      One-line joke