Python: Converting a queryset in a list of tuples
<p>i want to turn a queryset into a list of tuples. "result" ist what it should look like:</p>

<pre><code>queryset = [{x:'1',y:'a'}, {x:'2',y:'b'}]
result = [(1,'a'),(2,'b')]
</code></pre>

<p>So the solution i do have right now is this one, but it seems to me that there could be a way to shorten the code, and make it more efficient. Is there a way?</p>

<p>My current solution:</p>

<pre><code>result = []
for dic in queryset:
    result.append((dic[x],dic[y]))
</code></pre>

<p>Use list comprehension and <code>dict.values()</code></p>

<pre><code>&gt;&gt;&gt; queryset = [{'x': '1', 'y': 'a'}, {'x': '2', 'y': 'b'}]
&gt;&gt;&gt; result = [tuple(v.values()) for v in queryset]
&gt;&gt;&gt; result
    [('1', 'a'), ('2', 'b')]
</code></pre>

<p><strong>UPDATE</strong></p>

<p>as @aneroid reasonably mentioned, since <code>dict</code> object are not ordered the code snippet could return different order in <code>tuple</code></p>

<p>So since i don't want to add duplicate solution. There is one option, not so elegant, and maybe with a lack of efficiency, to use <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="nofollow"><code>OrderedDict</code></a></p>

<pre><code>&gt;&gt;&gt; from collections import OrderedDict
&gt;&gt;&gt; queryset = [{'x': '1', 'y': 'a'}, {'x': '2', 'y': 'b'}]
&gt;&gt;&gt; order = ('x', 'y')
&gt;&gt;&gt; result = [tuple(OrderedDict((k, v[k]) for k in myorder).values()) for v in queryset]
&gt;&gt;&gt; result
    [('1', 'a'), ('2', 'b')]
</code></pre>

<p>But i personally think that @PadraicCunningham 's <a href="http://stackoverflow.com/a/39702851/3124746">solution</a> is the most elegant here.</p>

python django performance