Fastest way to process a python list of tuples
<p>In a Django project, I have a python list of tuples like so:</p>

<pre><code>users_and_values = [(user_id,value),(user_id,value),......]
</code></pre>

<p>where <code>value</code> can either be 0.0 or 1.0 (float). Given this list, I need to create a new one, which is like so:</p>

<pre><code>[(user_object,value),(user_object,value),......]
</code></pre>

<p>where <code>user_object</code> is the object associated with each <code>user_id</code> (containing user attributes and such).</p>

<p><strong>What is the most efficient way to achieve this (performance and correctness both matter)?</strong> Currently, I'm trying to achieve that as follows in a Django view:</p>

<pre><code>    user_ids = [user_id for user_id, value in users_and_values]
    user_objs = User.objects.filter(id__in=user_ids)
    context["votes"] = [(user_objs(user_id),value) for user_id, value in users_and_votes]
</code></pre>

<p>This gives me the error: </p>

<blockquote>
  <p>'QuerySet' object is not callable</p>
</blockquote>

<p>I could also have tried <code>[(User.object.get(id=user_id),value) for user_id, value in users_and_values]</code>, but that would be too many DB calls. So can anyone chime in with what I'm doing wrong, and the correct solution? Thanks in advance. </p>

<p><code>user_objs</code> is an unordered collection of users. You have to manually map the user ids to the corresponding values by iterating over it:</p>

<pre><code>user_ids = [user_id for user_id, value in users_and_values]
user_objs = User.objects.filter(id__in=user_ids)

ids_to_values = dict(users_and_values)  # {id1: value1, ...}
context["votes"] = [(user, ids_to_values[user.id]) for user in user_objs]
</code></pre>

python django