Search code examples
pythonlistdictionaryliterate-programming

Column List of Dictionaries Create Columns


I have a column, X, where the rows' values are a list of dictionaries. I.e.

row 1 = [{category: **1**, outcome: 1444}, {category: **3**, outcome: 12}, {category: **3**, outcome: 11},... ]

row 2 = [{category: 2, outcome: 1555}, {category: 5, outcome: 42},...]

How can I create columns of each key present in X to then populate with values from the list of dictionaries from each row?

So for row 1, I'd populate a column, 1, with 1444... and column 3, with 12, 11 (2 values separated by a comma).


Solution

  • Here's one way to solve it.

    Given:

    row 1 = [{category: 1, outcome: 1444}, {category: 3, outcome: 12}, {category: 3, outcome: 11},... ]
    
    row 2 = [{category: 2, outcome: 1555}, {category: 5, outcome: 42},...]
    

    Format the rows so that they look like:

    new_row_1 = { 
         1: [1444, ...],
         3: [1444, 12, ...], 
          ...
    }
    
    new_row_2 = {
         2: [1555, ...], 
         5: [42, ...],
         ...
    }
    

    Then, you can just loop over each row and call .join().

    Here is some pseudocode :)

    RESULT_GROUPS = {}
    FOREACH row_id, row in rows
       FOREACH item in row
          RESULT_GROUPS[row_id][ item[category] ] = item[value]
    
       FOREACH group_id, group in RESULT_GROUPS[row_id]
          RESULT_GROUPS[row_id][ group_id ] = group.join(',')