title: Sort list of dict by key with different types in Python 3
body: <p>I have a method that group a list of dict by a key. To do it I found <a href="https://stackoverflow.com/a/16176538/8160995">here</a> that I have to use the <code>groupby</code> function but before I have to sort the list. Here is my method right now:</p>
  
  <pre><code>def group_list_by_key(data, key):
      data.sort(key=lambda x: x[key])
      result = []
      for k, v in groupby(data, key=lambda x: x[key]):
          result.append(list(v))
      return result
  </code></pre>
  
  <p>This piece of code works only if every key is defined in all the dicts and the values are all of the same type. However, where I use this method I don't know if the key is defined everywhere and if they are of the same type. On Python 2.x I know that exists <a href="https://docs.python.org/2.7/library/functions.html?highlight=sorted#sorted" rel="nofollow noreferrer"><code>sorted</code></a> function with <code>cmp</code> parameter that could do a custom sort but from <a href="https://docs.python.org/3/whatsnew/3.0.html#ordering-comparisons" rel="nofollow noreferrer">Python 3.x</a> this isn't possible anymore. Is there a way to make a custom sort? I am thinking about use the classic sort by <code>&lt;</code> and sorting also by typename. </p>
  
  <p>By now I thought about use the get function and cast to string in the sort like</p>
  
  <pre><code>data.sort(key=lambda x: str(x.get(key)))
  ...
  for k, v in groupby(data, key=lambda x: x.get(key)):
  </code></pre>
  
  <p>It only overcomes in case of string, numeric and None content but not a generic object and it breaks easily if for example I execute</p>
  
  <pre><code>a = [{'b': 0, 'c': 1}, {'b': '0'}, {'b': 0, 'c': 2}, {'b': 1}, {'c': 3}]
  group_list_by_key(a, 'b')
  </code></pre>
  
  <p>The output is</p>
  
  <pre><code>[[{'b': 0, 'c': 1}], [{'b': '0'}], [{'b': 0, 'c': 2}], [{'b': 1}], [{'c': 3}]]
  </code></pre>
  
  <p>instead of what I expect should be (order of lists is not a problem)</p>
  
  <pre><code>[[{'b': 0, 'c': 1}, {'b': 0, 'c': 2}], [{'b': '0'}], [{'b': 1}], [{'c': 3}]]
  </code></pre>