Acessing rows and columns in dictionary
<p>I have a dictionary that has its keys as tuples and values assigned to these keys.</p>

<p>I want to perform a set of actions based on the keys positions.</p>

<p>Here is my code that I have written so far.</p>

<p>Dictionary:</p>

<pre><code>p={(0, 1): 2, (1, 2): 6, (0, 0): 1, (2, 0): 7, (1, 0): 4, (2, 2): 9, (1, 1): 5, (2, 1): 8, (0, 2): 3}
</code></pre>

<p>Desired output is:</p>

<p>I want the values of individual rows as shown below.</p>

<pre><code>q=[[1,2,3], [4,5,6], [7,8,9]]
</code></pre>

<p>I wrote this code that can do this trick for columns:</p>

<pre><code>r=[[p[(x,y)] for x in range(3)] for y in range(3)]
</code></pre>

<p>for which the output looks like this:</p>

<pre><code>r=[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
</code></pre>

<p>I know how to do this with the following set of code:</p>

<pre><code>z=[]
for i in range(3):
    z.append([p[i,j] for j in range(3)])
</code></pre>

<p>Which gives me:</p>

<pre><code>z=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code></pre>

<p>My question is, can I do that operation in just one list comprehension?</p>

<p>Thanks in advance.</p>

<p>I had tried to do several things in the code. I had written it but did not realize that and went on trying different combinations with code.</p>

<p>Here is the answer:</p>

<pre><code>z=[[p[(i,j)] for j in range(3)] for i in range(3)]
</code></pre>

<p>Thanks!</p>

python dictionary