'How to convert a list of tuples to a matrix?

I have the following list of tuples:

list = [(House, Dog, 7), (House, Cat, 5), (Garden, Dog, 4), (Garden, Cat, 3), (Park,Mouse,2)]

I am looking for a matrix with the following structure:

result = [
          ['' ,  Dog,  Cat, Mouse],
          [House,  7,    5,    ''],
          [Garden, 4,    3,    ''],
          [Park,  '',   '',    2 ]
         ]  


Solution 1:[1]

from collections import Counter

data = [("House", "Dog", 7), ("House", "Cat", 5), ("Garden", "Dog", 4), ("Garden", "Cat", 3), ("Park", "Mouse", 2)]

header = [""]
column = [""]
counts = Counter();

for place, animal, count in data:
    if animal not in header:
        header.append(animal)
    if place not in column:
        column.append(place)

    counts[(place, animal)] += count

result = [header]
for (place, animal), count in counts.items():
    col = header.index(animal)
    row = column.index(place)
    if row >= len(result):
        result.append([place] + [""] * (len(header) - 1))

    result[row][col] = count

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lightalchemist