title: How to group similar items in a list?
body: <p>I am looking to group similar items in a list based on the first three characters in the string.  For example:</p>
  
  <pre><code>test = ['abc_1_2', 'abc_2_2', 'hij_1_1', 'xyz_1_2', 'xyz_2_2']
  </code></pre>
  
  <p>How can I group the above list items into groups based on the first grouping of letters (e.g. <code>'abc'</code>)? The following is the intended output:</p>
  
  <pre><code>output = {1: ('abc_1_2', 'abc_2_2'), 2: ('hij_1_1',), 3: ('xyz_1_2', 'xyz_2_2')}
  </code></pre>
  
  <p>or </p>
  
  <pre><code>output = [['abc_1_2', 'abc_2_2'], ['hij_1_1'], ['xyz_1_2', 'xyz_2_2']]
  </code></pre>
  
  <hr>
  
  <p>I have tried using <code>itertools.groupby</code> to accomplish this without success:</p>
  
  <pre><code>&gt;&gt;&gt; import os, itertools
  &gt;&gt;&gt; test = ['abc_1_2', 'abc_2_2', 'hij_1_1', 'xyz_1_2', 'xyz_2_2']
  &gt;&gt;&gt; [list(g) for k.split("_")[0], g in itertools.groupby(test)]
  [['abc_1_2'], ['abc_2_2'], ['hij_1_1'], ['xyz_1_2'], ['xyz_2_2']]
  </code></pre>
  
  <hr>
  
  <p>I have looked at the following posts without success:</p>
  
  <p><a href="https://stackoverflow.com/questions/5370294/how-to-merge-similar-items-in-a-list">How to merge similar items in a list</a>.  The example groups similar items (e.g. <code>'house'</code> and <code>'Hose'</code>) using an approach that is overly complicated for my example.</p>
  
  <p><a href="https://stackoverflow.com/questions/7025581/how-can-i-group-equivalent-items-together-in-a-python-list">How can I group equivalent items together in a Python list?</a>.  This is where I found the idea for the list comprehension.</p>