Build 2D array using append
<p>Python: I would like to read set of data</p>

<pre><code>(category, value): (0, 1) (0, 2) (1, 3) (1, 4)
</code></pre>

<p>To an array as</p>

<pre><code>[[1, 2],[3, 4]]
</code></pre>

<p>Since max number of category is unknown, I would like to create 2D-array dynamically using "append" method.</p>

<p>I wrote a sample code:</p>

<pre><code>data = []
data.append([])

data[0].append(1)
data[0].append(2)

try:
  print (data[1])
except IndexError:
  data.append([])
finally:
  data[1].append(3)
  data[1].append(4)

print(data)
</code></pre>

<p>But, I understand that the code is really ugly because I am using "print" to check the access to <code>data[1]</code>.</p>

<p>Is there any more beautiful solution for this problem?</p>

<p>Use <code>itertools.groupby</code>:</p>

<pre><code>import itertools

a = [(0, 1), (0, 2), (1, 3), (1, 4)]
g = itertools.groupby(a, key=lambda x: x[0])
g = [list(i[1]) for i in g]
</code></pre>

python list append