Python 2D list to dictionary










1















I have a 2 Dimensional list and have to get 2 columns from the 2D list and place the values from each column as key:value pairs.



Example:



table = [[15, 29, 6, 2],
[16, 9, 8, 0],
[7, 27, 16, 0]]

def averages(table, col, by):

columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

avgdict =
avgdict[groupby] = [columns]
print(avgdict)

averages(table, 1, 3)


Output is:



(2, 0, 0): [(29, 9, 27)]


I am trying to get the output to equal:



0:36, 2:29


So essentially the 2 keys of 0 have their values added



I'm having a hard time understanding how to separate each key with their values
and then adding the values together if the keys are equal.



Edit: I'm only using Python Standard library, and not implementing numpy for this problem.










share|improve this question



















  • 3





    Sorry, it is not clear to me what you would like to achieve. Also not clear why the question is tagged with "machine-learning"

    – g.a
    Nov 14 '18 at 3:33















1















I have a 2 Dimensional list and have to get 2 columns from the 2D list and place the values from each column as key:value pairs.



Example:



table = [[15, 29, 6, 2],
[16, 9, 8, 0],
[7, 27, 16, 0]]

def averages(table, col, by):

columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

avgdict =
avgdict[groupby] = [columns]
print(avgdict)

averages(table, 1, 3)


Output is:



(2, 0, 0): [(29, 9, 27)]


I am trying to get the output to equal:



0:36, 2:29


So essentially the 2 keys of 0 have their values added



I'm having a hard time understanding how to separate each key with their values
and then adding the values together if the keys are equal.



Edit: I'm only using Python Standard library, and not implementing numpy for this problem.










share|improve this question



















  • 3





    Sorry, it is not clear to me what you would like to achieve. Also not clear why the question is tagged with "machine-learning"

    – g.a
    Nov 14 '18 at 3:33













1












1








1








I have a 2 Dimensional list and have to get 2 columns from the 2D list and place the values from each column as key:value pairs.



Example:



table = [[15, 29, 6, 2],
[16, 9, 8, 0],
[7, 27, 16, 0]]

def averages(table, col, by):

columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

avgdict =
avgdict[groupby] = [columns]
print(avgdict)

averages(table, 1, 3)


Output is:



(2, 0, 0): [(29, 9, 27)]


I am trying to get the output to equal:



0:36, 2:29


So essentially the 2 keys of 0 have their values added



I'm having a hard time understanding how to separate each key with their values
and then adding the values together if the keys are equal.



Edit: I'm only using Python Standard library, and not implementing numpy for this problem.










share|improve this question
















I have a 2 Dimensional list and have to get 2 columns from the 2D list and place the values from each column as key:value pairs.



Example:



table = [[15, 29, 6, 2],
[16, 9, 8, 0],
[7, 27, 16, 0]]

def averages(table, col, by):

columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

avgdict =
avgdict[groupby] = [columns]
print(avgdict)

averages(table, 1, 3)


Output is:



(2, 0, 0): [(29, 9, 27)]


I am trying to get the output to equal:



0:36, 2:29


So essentially the 2 keys of 0 have their values added



I'm having a hard time understanding how to separate each key with their values
and then adding the values together if the keys are equal.



Edit: I'm only using Python Standard library, and not implementing numpy for this problem.







python machine-learning






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 4:27









Andreas

1,8312918




1,8312918










asked Nov 14 '18 at 3:29









jamesjames

506




506







  • 3





    Sorry, it is not clear to me what you would like to achieve. Also not clear why the question is tagged with "machine-learning"

    – g.a
    Nov 14 '18 at 3:33












  • 3





    Sorry, it is not clear to me what you would like to achieve. Also not clear why the question is tagged with "machine-learning"

    – g.a
    Nov 14 '18 at 3:33







3




3





Sorry, it is not clear to me what you would like to achieve. Also not clear why the question is tagged with "machine-learning"

– g.a
Nov 14 '18 at 3:33





Sorry, it is not clear to me what you would like to achieve. Also not clear why the question is tagged with "machine-learning"

– g.a
Nov 14 '18 at 3:33












3 Answers
3






active

oldest

votes


















2














You can create an empty dictionary, then iterate through every element of groupby. If the element in groupby exist in the dictionary, then add the corresponding element in columns to the values in the dictionary. Otherwise, add the element in groupby as key and the corresponding element in columns as value.The implementation is as follows:



table = [[15, 29, 6, 2],
[16, 9, 8, 0],
[7, 27, 16, 0]]

def averages(table, col, by):
columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

avgdict =

for x in range(len(groupby)):
key = groupby[x]
if key in avgdict:
avgdict[key] += columns[x]
else:
avgdict[key] = columns[x]

print(avgdict)

averages(table, 1, 3)


Otherwise, if you want to keep your initial avgdict, then you can change the averages() function to



def averages(table, col, by):
columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

avgdict =
avgdict[groupby] = [columns]

newdict =

for key in avgdict:
for x in range(len(key)):
if key[x] in newdict:
newdict[key[x]] += avgdict[key][0][x]
else:
newdict[key[x]] = avgdict[key][0][x]

print(newdict)





share|improve this answer






























    1














    It took me a minute to figure out what you were trying to accomplish because your function and variable names reference averages but your output is a sum.



    Based on your output, it seems you're trying to aggregate row values in a given column by a group in another column.



    Here's a recommended solution (which likely could be reduced to a one-liner via list comprehension). This loops through the unique (using set) values (b) in your group by, creates a dictionary key (agg_dict[b]) for the group by being processed, and sums all rows in a given column (col) if the group by is being processed (table[i][by] == by).



    table = [[15, 29, 6, 2],
    [16, 9, 8, 0],
    [7, 27, 16, 0]]


    def aggregate(tbl, col, by):
    agg_dict =
    for b in list(set([table[i][by] for i in range(len(table))]))
    agg_dict[b] = sum([table[i][col] for i in range(len(table)) if table[i][by] == b])
    print(agg_dict)


    aggregate(table, 1, 3)





    share|improve this answer

























    • my apologies for making it unclear, i missnamed the function.

      – james
      Nov 14 '18 at 4:00






    • 1





      No problem. I was just trying to help clarify the ask. When you get to a resolution, please remember to up-vote useful things and accept your favorite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question.

      – rs311
      Nov 14 '18 at 4:07


















    1














    Sorry for joining the party late. You can also try the following answer. It doesn't use numpy, and is based on the use of sets to find unique elements in groupby.



    table = [[15, 29, 6, 2],
    [16, 9, 8, 0],
    [7, 27, 16, 0]]

    def averages(table, col, by):
    columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
    groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

    '''groupby_unq: tuple data type
    stores list of unique entries in groupby.'''
    groupby_unq = tuple(set(groupby))

    '''avg: numpy.ndarray data type
    numpy array of zeros of same length as groupby_unq.'''
    avg = np.zeros( len(groupby_unq) )

    for i in range(len(groupby)):
    for j in range(len(groupby_unq)):
    if(groupby[i]==groupby_unq[j]): avg[j]+=columns[i]

    avgdict = dict( (groupby_unq[i], avg[i]) for i in range(len(avg)) )

    return avgdict

    result = averages(table, 1, 3)
    print result

    0: 36.0, 2: 29.0





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



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292779%2fpython-2d-list-to-dictionary%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      You can create an empty dictionary, then iterate through every element of groupby. If the element in groupby exist in the dictionary, then add the corresponding element in columns to the values in the dictionary. Otherwise, add the element in groupby as key and the corresponding element in columns as value.The implementation is as follows:



      table = [[15, 29, 6, 2],
      [16, 9, 8, 0],
      [7, 27, 16, 0]]

      def averages(table, col, by):
      columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
      groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

      avgdict =

      for x in range(len(groupby)):
      key = groupby[x]
      if key in avgdict:
      avgdict[key] += columns[x]
      else:
      avgdict[key] = columns[x]

      print(avgdict)

      averages(table, 1, 3)


      Otherwise, if you want to keep your initial avgdict, then you can change the averages() function to



      def averages(table, col, by):
      columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
      groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

      avgdict =
      avgdict[groupby] = [columns]

      newdict =

      for key in avgdict:
      for x in range(len(key)):
      if key[x] in newdict:
      newdict[key[x]] += avgdict[key][0][x]
      else:
      newdict[key[x]] = avgdict[key][0][x]

      print(newdict)





      share|improve this answer



























        2














        You can create an empty dictionary, then iterate through every element of groupby. If the element in groupby exist in the dictionary, then add the corresponding element in columns to the values in the dictionary. Otherwise, add the element in groupby as key and the corresponding element in columns as value.The implementation is as follows:



        table = [[15, 29, 6, 2],
        [16, 9, 8, 0],
        [7, 27, 16, 0]]

        def averages(table, col, by):
        columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
        groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

        avgdict =

        for x in range(len(groupby)):
        key = groupby[x]
        if key in avgdict:
        avgdict[key] += columns[x]
        else:
        avgdict[key] = columns[x]

        print(avgdict)

        averages(table, 1, 3)


        Otherwise, if you want to keep your initial avgdict, then you can change the averages() function to



        def averages(table, col, by):
        columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
        groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

        avgdict =
        avgdict[groupby] = [columns]

        newdict =

        for key in avgdict:
        for x in range(len(key)):
        if key[x] in newdict:
        newdict[key[x]] += avgdict[key][0][x]
        else:
        newdict[key[x]] = avgdict[key][0][x]

        print(newdict)





        share|improve this answer

























          2












          2








          2







          You can create an empty dictionary, then iterate through every element of groupby. If the element in groupby exist in the dictionary, then add the corresponding element in columns to the values in the dictionary. Otherwise, add the element in groupby as key and the corresponding element in columns as value.The implementation is as follows:



          table = [[15, 29, 6, 2],
          [16, 9, 8, 0],
          [7, 27, 16, 0]]

          def averages(table, col, by):
          columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
          groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

          avgdict =

          for x in range(len(groupby)):
          key = groupby[x]
          if key in avgdict:
          avgdict[key] += columns[x]
          else:
          avgdict[key] = columns[x]

          print(avgdict)

          averages(table, 1, 3)


          Otherwise, if you want to keep your initial avgdict, then you can change the averages() function to



          def averages(table, col, by):
          columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
          groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

          avgdict =
          avgdict[groupby] = [columns]

          newdict =

          for key in avgdict:
          for x in range(len(key)):
          if key[x] in newdict:
          newdict[key[x]] += avgdict[key][0][x]
          else:
          newdict[key[x]] = avgdict[key][0][x]

          print(newdict)





          share|improve this answer













          You can create an empty dictionary, then iterate through every element of groupby. If the element in groupby exist in the dictionary, then add the corresponding element in columns to the values in the dictionary. Otherwise, add the element in groupby as key and the corresponding element in columns as value.The implementation is as follows:



          table = [[15, 29, 6, 2],
          [16, 9, 8, 0],
          [7, 27, 16, 0]]

          def averages(table, col, by):
          columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
          groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

          avgdict =

          for x in range(len(groupby)):
          key = groupby[x]
          if key in avgdict:
          avgdict[key] += columns[x]
          else:
          avgdict[key] = columns[x]

          print(avgdict)

          averages(table, 1, 3)


          Otherwise, if you want to keep your initial avgdict, then you can change the averages() function to



          def averages(table, col, by):
          columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
          groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

          avgdict =
          avgdict[groupby] = [columns]

          newdict =

          for key in avgdict:
          for x in range(len(key)):
          if key[x] in newdict:
          newdict[key[x]] += avgdict[key][0][x]
          else:
          newdict[key[x]] = avgdict[key][0][x]

          print(newdict)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 14 '18 at 3:44









          AndreasAndreas

          1,8312918




          1,8312918























              1














              It took me a minute to figure out what you were trying to accomplish because your function and variable names reference averages but your output is a sum.



              Based on your output, it seems you're trying to aggregate row values in a given column by a group in another column.



              Here's a recommended solution (which likely could be reduced to a one-liner via list comprehension). This loops through the unique (using set) values (b) in your group by, creates a dictionary key (agg_dict[b]) for the group by being processed, and sums all rows in a given column (col) if the group by is being processed (table[i][by] == by).



              table = [[15, 29, 6, 2],
              [16, 9, 8, 0],
              [7, 27, 16, 0]]


              def aggregate(tbl, col, by):
              agg_dict =
              for b in list(set([table[i][by] for i in range(len(table))]))
              agg_dict[b] = sum([table[i][col] for i in range(len(table)) if table[i][by] == b])
              print(agg_dict)


              aggregate(table, 1, 3)





              share|improve this answer

























              • my apologies for making it unclear, i missnamed the function.

                – james
                Nov 14 '18 at 4:00






              • 1





                No problem. I was just trying to help clarify the ask. When you get to a resolution, please remember to up-vote useful things and accept your favorite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question.

                – rs311
                Nov 14 '18 at 4:07















              1














              It took me a minute to figure out what you were trying to accomplish because your function and variable names reference averages but your output is a sum.



              Based on your output, it seems you're trying to aggregate row values in a given column by a group in another column.



              Here's a recommended solution (which likely could be reduced to a one-liner via list comprehension). This loops through the unique (using set) values (b) in your group by, creates a dictionary key (agg_dict[b]) for the group by being processed, and sums all rows in a given column (col) if the group by is being processed (table[i][by] == by).



              table = [[15, 29, 6, 2],
              [16, 9, 8, 0],
              [7, 27, 16, 0]]


              def aggregate(tbl, col, by):
              agg_dict =
              for b in list(set([table[i][by] for i in range(len(table))]))
              agg_dict[b] = sum([table[i][col] for i in range(len(table)) if table[i][by] == b])
              print(agg_dict)


              aggregate(table, 1, 3)





              share|improve this answer

























              • my apologies for making it unclear, i missnamed the function.

                – james
                Nov 14 '18 at 4:00






              • 1





                No problem. I was just trying to help clarify the ask. When you get to a resolution, please remember to up-vote useful things and accept your favorite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question.

                – rs311
                Nov 14 '18 at 4:07













              1












              1








              1







              It took me a minute to figure out what you were trying to accomplish because your function and variable names reference averages but your output is a sum.



              Based on your output, it seems you're trying to aggregate row values in a given column by a group in another column.



              Here's a recommended solution (which likely could be reduced to a one-liner via list comprehension). This loops through the unique (using set) values (b) in your group by, creates a dictionary key (agg_dict[b]) for the group by being processed, and sums all rows in a given column (col) if the group by is being processed (table[i][by] == by).



              table = [[15, 29, 6, 2],
              [16, 9, 8, 0],
              [7, 27, 16, 0]]


              def aggregate(tbl, col, by):
              agg_dict =
              for b in list(set([table[i][by] for i in range(len(table))]))
              agg_dict[b] = sum([table[i][col] for i in range(len(table)) if table[i][by] == b])
              print(agg_dict)


              aggregate(table, 1, 3)





              share|improve this answer















              It took me a minute to figure out what you were trying to accomplish because your function and variable names reference averages but your output is a sum.



              Based on your output, it seems you're trying to aggregate row values in a given column by a group in another column.



              Here's a recommended solution (which likely could be reduced to a one-liner via list comprehension). This loops through the unique (using set) values (b) in your group by, creates a dictionary key (agg_dict[b]) for the group by being processed, and sums all rows in a given column (col) if the group by is being processed (table[i][by] == by).



              table = [[15, 29, 6, 2],
              [16, 9, 8, 0],
              [7, 27, 16, 0]]


              def aggregate(tbl, col, by):
              agg_dict =
              for b in list(set([table[i][by] for i in range(len(table))]))
              agg_dict[b] = sum([table[i][col] for i in range(len(table)) if table[i][by] == b])
              print(agg_dict)


              aggregate(table, 1, 3)






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 14 '18 at 4:24

























              answered Nov 14 '18 at 3:50









              rs311rs311

              1439




              1439












              • my apologies for making it unclear, i missnamed the function.

                – james
                Nov 14 '18 at 4:00






              • 1





                No problem. I was just trying to help clarify the ask. When you get to a resolution, please remember to up-vote useful things and accept your favorite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question.

                – rs311
                Nov 14 '18 at 4:07

















              • my apologies for making it unclear, i missnamed the function.

                – james
                Nov 14 '18 at 4:00






              • 1





                No problem. I was just trying to help clarify the ask. When you get to a resolution, please remember to up-vote useful things and accept your favorite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question.

                – rs311
                Nov 14 '18 at 4:07
















              my apologies for making it unclear, i missnamed the function.

              – james
              Nov 14 '18 at 4:00





              my apologies for making it unclear, i missnamed the function.

              – james
              Nov 14 '18 at 4:00




              1




              1





              No problem. I was just trying to help clarify the ask. When you get to a resolution, please remember to up-vote useful things and accept your favorite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question.

              – rs311
              Nov 14 '18 at 4:07





              No problem. I was just trying to help clarify the ask. When you get to a resolution, please remember to up-vote useful things and accept your favorite answer (even if you have to write it yourself), so Stack Overflow can properly archive the question.

              – rs311
              Nov 14 '18 at 4:07











              1














              Sorry for joining the party late. You can also try the following answer. It doesn't use numpy, and is based on the use of sets to find unique elements in groupby.



              table = [[15, 29, 6, 2],
              [16, 9, 8, 0],
              [7, 27, 16, 0]]

              def averages(table, col, by):
              columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
              groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

              '''groupby_unq: tuple data type
              stores list of unique entries in groupby.'''
              groupby_unq = tuple(set(groupby))

              '''avg: numpy.ndarray data type
              numpy array of zeros of same length as groupby_unq.'''
              avg = np.zeros( len(groupby_unq) )

              for i in range(len(groupby)):
              for j in range(len(groupby_unq)):
              if(groupby[i]==groupby_unq[j]): avg[j]+=columns[i]

              avgdict = dict( (groupby_unq[i], avg[i]) for i in range(len(avg)) )

              return avgdict

              result = averages(table, 1, 3)
              print result

              0: 36.0, 2: 29.0





              share|improve this answer





























                1














                Sorry for joining the party late. You can also try the following answer. It doesn't use numpy, and is based on the use of sets to find unique elements in groupby.



                table = [[15, 29, 6, 2],
                [16, 9, 8, 0],
                [7, 27, 16, 0]]

                def averages(table, col, by):
                columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
                groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

                '''groupby_unq: tuple data type
                stores list of unique entries in groupby.'''
                groupby_unq = tuple(set(groupby))

                '''avg: numpy.ndarray data type
                numpy array of zeros of same length as groupby_unq.'''
                avg = np.zeros( len(groupby_unq) )

                for i in range(len(groupby)):
                for j in range(len(groupby_unq)):
                if(groupby[i]==groupby_unq[j]): avg[j]+=columns[i]

                avgdict = dict( (groupby_unq[i], avg[i]) for i in range(len(avg)) )

                return avgdict

                result = averages(table, 1, 3)
                print result

                0: 36.0, 2: 29.0





                share|improve this answer



























                  1












                  1








                  1







                  Sorry for joining the party late. You can also try the following answer. It doesn't use numpy, and is based on the use of sets to find unique elements in groupby.



                  table = [[15, 29, 6, 2],
                  [16, 9, 8, 0],
                  [7, 27, 16, 0]]

                  def averages(table, col, by):
                  columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
                  groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

                  '''groupby_unq: tuple data type
                  stores list of unique entries in groupby.'''
                  groupby_unq = tuple(set(groupby))

                  '''avg: numpy.ndarray data type
                  numpy array of zeros of same length as groupby_unq.'''
                  avg = np.zeros( len(groupby_unq) )

                  for i in range(len(groupby)):
                  for j in range(len(groupby_unq)):
                  if(groupby[i]==groupby_unq[j]): avg[j]+=columns[i]

                  avgdict = dict( (groupby_unq[i], avg[i]) for i in range(len(avg)) )

                  return avgdict

                  result = averages(table, 1, 3)
                  print result

                  0: 36.0, 2: 29.0





                  share|improve this answer















                  Sorry for joining the party late. You can also try the following answer. It doesn't use numpy, and is based on the use of sets to find unique elements in groupby.



                  table = [[15, 29, 6, 2],
                  [16, 9, 8, 0],
                  [7, 27, 16, 0]]

                  def averages(table, col, by):
                  columns = tuple(([table[i][col] for i in range(len(table))])) #Place col column into tuple so it can be placed into dictionary
                  groupby = tuple(([table[i][by] for i in range(len(table))])) #Place groupby column into tuple so it can be placed into dictionary

                  '''groupby_unq: tuple data type
                  stores list of unique entries in groupby.'''
                  groupby_unq = tuple(set(groupby))

                  '''avg: numpy.ndarray data type
                  numpy array of zeros of same length as groupby_unq.'''
                  avg = np.zeros( len(groupby_unq) )

                  for i in range(len(groupby)):
                  for j in range(len(groupby_unq)):
                  if(groupby[i]==groupby_unq[j]): avg[j]+=columns[i]

                  avgdict = dict( (groupby_unq[i], avg[i]) for i in range(len(avg)) )

                  return avgdict

                  result = averages(table, 1, 3)
                  print result

                  0: 36.0, 2: 29.0






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 15 '18 at 4:22

























                  answered Nov 14 '18 at 20:43









                  Siddharth SatpathySiddharth Satpathy

                  481314




                  481314



























                      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.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292779%2fpython-2d-list-to-dictionary%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

                      Top Tejano songwriter Luis Silva dead of heart attack at 64

                      政党

                      天津地下鉄3号線