Python sort (json) list by calculated value
<p>I have originally a JSON format with products and the challenge is to sort this list by the best price per unit (prdata3, prdata2, prdata1): </p>

<pre><code>{'prdata3': {'variation': 'stand', 'price': '78 54', 'amount': '6', 
      'url': 'https://www.productwebaddress.com/3'}, 
 'prdata2': {'variation': 'stand', 'price': '15 24', 'amount': '1', 
      'url': 'https://www.productwebaddress.com/2'}, 
 'prdata1': {'variation': 'vc', 'price': '78 54', 'amount': '12', 
      'url': 'https://www.productwebaddress.com/1'}}
</code></pre>

<p>The price needs to be divided by the amount and the list needs to be sorted by this value, so in my example the output need to be (prdata1 (6,55), prdata3 (13,09), prdata2 (15,24)):</p>

<pre><code>{'prdata1': {'variation': 'vc', 'price': '78 54', 'amount': '12', 'url': 'https://www.productwebaddress.com/1'}, 'prdata3': {'variation': 'stand', 'price': '78 54', 'amount': '6', 'url': 'https://www.productwebaddress.com/3'}, 'prdata2': {'variation': 'stand', 'price': '15 24', 'amount': '1', 'url': 'https://www.productwebaddress.com/2'}}
</code></pre>

<p>What is the best strategy here? I gave my best to first go in there with "for each", looking for the price, replace the space with a dot, divide it with the amount and now use this result to sort my list with something like: <code>sorted(mylist.items(), key=lambda t: t[1])</code> ... but my result as key, right? </p>

<p>You can't sort a dictionary, as dictionary have no order. </p>

<p>But you can do the following:</p>

<pre><code>print sorted(a.items(),key=lambda x:float(x[1]['price'])/int(x[1]['amount']))
</code></pre>

<p>Output:</p>

<pre><code>[('prdata1', {'url': 'https://www.productwebaddress.com/1', 'price': '78.54', 'amount': '12', 'variation': 'vc'}), 
('prdata3', {'url': 'https://www.productwebaddress.com/3', 'price': '78.54', 'amount': '6', 'variation': 'stand'}), 
('prdata2', {'url': 'https://www.productwebaddress.com/2', 'price': '15.24', 'amount': '1', 'variation': 'stand'})]
</code></pre>

<p>And, you can use <code>collections.OrderedDict</code> to retain the dictionary structure if it really matters. </p>

<pre><code>from collections import OrderedDict
print OrderedDict(sorted(a.items(),key=lambda x:float(x[1]['price'])/int(x[1]['amount'])))
</code></pre>

<p>Output:</p>

<pre><code>OrderedDict([('prdata1', {'url': 'https://www.productwebaddress.com/1', 'price': '78.54', 'amount': '12', 'variation': 'vc'}), 
('prdata3', {'url': 'https://www.productwebaddress.com/3', 'price': '78.54', 'amount': '6', 'variation': 'stand'}), 
('prdata2', {'url': 'https://www.productwebaddress.com/2', 'price': '15.24', 'amount': '1', 'variation': 'stand'})])
</code></pre>

python json sorting