Python and flask, looping and printing data based on a variable
<p>I have a problem with looping in python and JSON based on a variable. What Im trying to do is to print just one row of JSON data based on one variable that is passed through.</p>

<p>Heres the code for the python file:</p>

<pre><code>@app.route('/&lt;artist_name&gt;/')
def artist(artist_name):
    list = [
        {'artist_name': 'Nirvana', 'album_name': 'Nevermind', 'date_of_release': '1993', 'img': 'https://upload.wikimedia.org/wikipedia/en/b/b7/NirvanaNevermindalbumcover.jpg'},
        {'artist_name': 'Eminem', 'album_name': 'Marshal Mathers LP', 'date_of_release': '2000', 'img': 'http://e.snmc.io/lk/f/l/6b09725acea3aefbafbf503a76885d0c/1612455.jpg'},
        {'artist_name': 'System of a Down', 'album_name': 'Toxicity', 'date_of_release': '2001', 'img': 'http://loudwire.com/files/2015/09/System-of-a-Down-Toxicity.png'},
        {'artist_name': 'Korn', 'album_name': 'Life is Peachy', 'date_of_release': '1996', 'img': 'http://loudwire.com/files/2014/01/Life-is-Peachy.jpg'}
    ]
    return render_template("artist.html", results=list, artist_name=artist_name)    
</code></pre>

<p>And this is my artist.html template:</p>

<pre><code>{% if results %}
&lt;ul&gt;
{% for item in results if item.artist_name == item.artist_name %}
    &lt;li&gt;{{ item.artist_name }}&lt;/li&gt;
    &lt;li&gt;{{ item.date_of_release}}&lt;/li&gt;
{% endfor %}
&lt;/ul&gt;
{% endif %}
</code></pre>

<p>What im trying to achieve is that when an "artist_name" variable is being passed I will be able to print "artist_name" variable and "date_of_release" variable but instead it prints all four records instead of one based on the variable "artist_name". Can anybody help me with this? Thank you.</p>

<p>In the comments, H J potter and Markus have it right: <em>however</em> I'ld be very careful over the url encoding of your url and enforcing capitlisation of the artist name: Is "System Of A Down" the same as "System of a Down", and does flask always decode correctly?</p>

<pre><code>{% if results %}
&lt;ul&gt;
{% for item in results if item.artist_name == artist_name %}
    &lt;li&gt;{{ item.artist_name }}&lt;/li&gt;
    &lt;li&gt;{{ item.date_of_release}}&lt;/li&gt;
{% endfor %}
&lt;/ul&gt;
{% endif %}
</code></pre>

<p>Have a look at <a href="http://stackoverflow.com/questions/497908/is-a-url-allowed-to-contain-a-space">Is a URL allowed to contain a space?</a> TLDR? "Shorter answer: no, you must encode a space; it is correct to encode a space as +, but only in the query string; in the path you must use %20."</p>

<p>I would also go further though and suggest a restructure of the code - try to keep business logic (i.e. deciding not to display or load all the data) in one file, the 'python', and the display logic (deciding to put them on bullet points or on divs) in the other (the 'template')</p>

python json loops variables flask