title: Sorting a list of dictionaries in Python 3
body: <p>I am trying to sort a list of dictionaries. My goal is to sort dictionaries with multiple (possibly the same) keys in the same way, even if the dictionaries are in a different order or if the keys are in the dictionary in a different order.</p>
  
  <p>In Python 2, I have used the following:</p>
  
  <pre><code>a = [{1: 2, 7: 8}, {7: 8, 3: 4}, {5: 6}]
  b = [{3: 4, 7: 8}, {7: 8, 1: 2}, {5: 6}]
  a.sort()
  b.sort()
  a
  Out[20]: [{5: 6}, {1: 2, 7: 8}, {3: 4, 7: 8}]
  b
  Out[21]: [{5: 6}, {1: 2, 7: 8}, {3: 4, 7: 8}]
  </code></pre>
  
  <p>This succeeds in my goal of creating two sorted dictionaries that look exactly the same.</p>
  
  <p>I am trying to do the same thing in Python 3, where .sort() does not work for a list of dictionaries.</p>
  
  <p>I have tried different ways.</p>
  
  <p>1.</p>
  
  <pre><code>sorted(a, key=lambda d: max(d.keys()))
  </code></pre>
  
  <p>This does not work:</p>
  
  <pre><code>a = [{1: 2, 7: 8}, {3: 4, 7: 8}, {5: 6}]
  b = [{3: 4, 7: 8}, {1: 2, 7: 8}, {5: 6}]
  a2 = sorted(a, key=lambda d: max(d.keys()))
  b2 = sorted(b, key=lambda d: max(d.keys()))
  a2
  Out[1]: [{5: 6}, {1: 2, 7: 8}, {7: 8, 3: 4}]
  b2
  Out[2]: [{5: 6}, {3: 4, 7: 8}, {7: 8, 1: 2}]
  </code></pre>
  
  <p>2.</p>
  
  <pre><code>a2 = sorted([list(zip(x.keys(),x.values())) for x in a])
  a3 = [{k: v for (k,v) in x} for x in a2]
  </code></pre>
  
  <p>This does not work:</p>
  
  <pre><code>a = [{1: 2, 7: 8}, {7: 8, 3: 4}, {5: 6}]
  b = [{3: 4, 7: 8}, {7: 8, 1: 2}, {5: 6}]
  a2 = sorted([list(zip(x.keys(),x.values())) for x in a])
  a3 = [{k: v for (k,v) in x} for x in a2]
  b2 = sorted([list(zip(x.keys(),x.values())) for x in b])
  b3 = [{k: v for (k,v) in x} for x in b2]
  a3
  Out[1]: [{1: 2, 7: 8}, {5: 6}, {7: 8, 3: 4}]
  b3
  Out[2]: [{3: 4, 7: 8}, {5: 6}, {7: 8, 1: 2}]
  </code></pre>
  
  <p>Does anyone have an idea how I can get the Python 2 result in Python 3??</p>