Tuples in python to 3D matrix
<p>I have a list of lists in python that contains the score of users in a game with different courses and levels. My tuple (users, courses, levels, scores). I ve got 20 users 4 courses and 10 levels. What I want is to create a 3D matrix which will have as dimensions users-courses-levels and as a value user score.  My tuples are as of the following:</p>

<pre><code>(110, u'Math', 1, 5)
(110, u'Sports', 1,  5)
(110, u'Geography', 1, 10)
(112, u'History', 1,  9)
(112, u'History', 2,  10)
... ... ... ... ... ... ..
</code></pre>

<p>How can I create the 3D matrix (putting zero in the fields that I dont have data)? </p>

<p>If you really need the data in that form, you could do something like:</p>

<pre><code>data = [(110, 'Math', 1, 5),
(110, 'Sports', 1,  5),
(110, 'Geography', 1, 10),
(112, 'History', 1,  9),
(112, 'History', 2,  10)] #I'm using Python 3 -- u'' is superfluous

dataDict = {(x,y,z):w for x,y,z,w in data}

users = [110,112] #extend as needed. Also -- easily grabbed by code
subjects = ['Math', 'Sports', 'Geography', 'History'] #etc
levels = [1,2] #etc.

#first create a matrix of the right shape initialized to zeros:

dataMatrix = [[[0 for k in range(len(levels))] for j in range(len(subjects))] for i in range(len(users))]

#then load the nonzeros:

for i,u in enumerate(users):
    for j,s in enumerate(subjects):
        for k,l in enumerate(levels):
            if (u,s,l) in dataDict: dataMatrix[i][j][k] = dataDict[u,s,l]
</code></pre>

<p>To view it, do something like:</p>

<pre><code>&gt;&gt;&gt; for layer in dataMatrix: print(layer)

[[5, 0], [5, 0], [10, 0], [0, 0]]
[[0, 0], [0, 0], [0, 0], [9, 10]]
</code></pre>

<p>the first layer is the 2-D matrix corresponding to the first user, etc.</p>

<p>Having done all this -- I really don't see any reason anybody would want to use <code>dataMatrix</code> rather than <code>dataDict</code>.</p>

python