Why use itertools.groupby instead of doing it yourself?
<pre><code>from collections import defaultdict
import itertools

items = [(0, 0), (0, 1), (1, 0), (1, 1)]

keyfunc = lambda x: x[0]

# Grouping yourself
item_map = defaultdict(list)
for item in items:
    item_map[keyfunc(item)].append(item)

# Using itertools.groupby
item_map = {}
for key, group in itertools.groupby(items, keyfunc):
    item_map[key] = [i for i in group]
</code></pre>

<p>What is so great about <code>itertools.groupby</code> that I should use it instead of doing it myself? Can it perform the grouping in less time complexity? Or, am I missing the point with my use case, and <code>groupby</code> should be used for other cases?</p>

<hr>

<p>Another poster mentioned that <code>itertools.groupby</code> will return a different result if the items to be grouped are not sorted by the key (or rather just that keys are consecutive to one another).</p>

<p>For example, with <code>items = [(0, 0), (1, 1), (0, 2)]</code>, if we don't sort on the key, <code>itertools.groupby</code> returns </p>

<pre><code>{0: [(0, 2)], 1: [(1, 1)]}
</code></pre>

<p>Whereas my implementation returns </p>

<pre><code>{0: [(0, 0), (0, 2)], 1: [(1, 1)]}
</code></pre>

<p>Unless I'm misunderstanding the point, it would seem that the DIY method is better because it doesn't require the data to be sorted.</p>

<p>Here is the <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow">documentation</a>:</p>

<blockquote>
  <p>Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None, key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function</p>
</blockquote>

<p>Generally the point of using iterators is to avoid keeping an entire data set in memory. In your example, it doesn't matter because:</p>

<ul>
<li>The input is already all in memory.</li>
<li>You're just dumping everything into a <code>dict</code>, so the output is also all in memory.</li>
</ul>

<blockquote>
  <p>Or, am I missing the point with my use case, and groupby should be used for other cases?</p>
</blockquote>

<p>I think that's an accurate assessment.</p>

<p>Suppose <code>items</code> is an iterator (e.g. let's say it's lines being read from stdin) and the output is something other than an in-memory data structure (e.g. stdout):</p>

<pre><code>for key, group in itertools.groupby(items, keyfunc):
    print("{}: {}".format(key, str([i for i in group])))
</code></pre>

<p>Now it would be less trivial to do that yourself.</p>

python