How to collect a record by a parameter python
<p>Python source :</p>

<pre><code>@app.route('/pret/&lt;int:idPret&gt;', methods=['GET'])
def descrire_un_pret(idPret):

    j = 0

    for j in prets:
        if prets[j]['id'] == idPret:
            reponse = make_response(json.dumps(prets[j],200))
            reponse.headers = {"Content-Type": "application/json"}
            return reponse
</code></pre>

<p>I would like to retrieve a record in the <code>prets</code> list by the <code>idPret</code> parameter. Nevertheless I get an error:</p>

<pre><code>TypeError: list indices must be integers, not dict
</code></pre>

<p><code>j</code> is not a number. <code>j</code> is one element in the <code>prets</code> list. Python loops are foreach loops. <code>if j['id'] == idPret:</code> would work:</p>

<pre><code>for j in prets:
    if j['id'] == idPret:
        reponse = make_response(json.dumps(j, 200))
        reponse.headers = {"Content-Type": "application/json"}
        return reponse
</code></pre>

<p>I'd use a different name here, and use the <a href="http://flask.pocoo.org/docs/0.11/api/#flask.json.jsonify" rel="nofollow"><code>flask.json.jsonify()</code> function</a> to create the response:</p>

<pre><code>from flask import jsonify

for pret in prets:
    if pret['id'] == idPret:
        return jsonify(pret)
</code></pre>

<p><code>jsonify()</code> takes care of converting to JSON and creating the response object with the right headers for you.</p>

python flask