JackJack
JackJack

Reputation: 193

Access a list of dictionaries inside of a dictionary in Django templates

I'm trying to access a list inside of my Django Html template, but I can't seem to grab the first element of the list the normal way by grabbing it via its index. In my views, I have a function edamam that calls the API endpoint and returns a JSON dictionary named ingredients.

Here's the function:

@login_required
def edamam(request):
    ingredients = {}
    if 'ingr' in request.GET:
        ingr = request.GET['ingr']
        app_key = APP_KEY
        app_id = APP_ID
        url = f'https://api.edamam.com/api/food-database/v2/parser?ingr={ingr}&app_id={app_id}&app_key={app_key}'
        response = requests.get(url)
        ingredients = response.json()
        print(f'Type: {type(ingredients)}')
        return render(request, 'todo/edamam.html', {'ingredients': ingredients})
    else:
        return render(request, 'todo/edamam.html', {'error': 'That item does not exist in the database.'})

I printed typeof(ingredients) to be certain I'm returning a dictionary and the printout does verify that in the console:

Type: <class 'dict'>

In my views edamam.html, I'm grabbing ingredients.parsed (ingredients is just a massive dictionary) because I'm trying to get the list named parsed in order to grab elements from that.

<div class="col-md-5">
   {% if ingredients %}
   <p>{{ ingredients.parsed }}</p>
   {% endif %} {% endblock %}
</div>

which returns:

[{'food': 

    {'foodId': 'food_bnxr4n3b1ld7i6ace2hkqbwm89du', 'label': 'cheeseburger', 'nutrients': {'ENERC_KCAL': 263.0, 'PROCNT': 12.97, 'FAT': 11.79, 'CHOCDF': 27.81, 'FIBTG': 1.1}
    , 'category': 'Generic foods', 'categoryLabel': 'food'}

}]

My question is, how do I get to the 'food' dictionary inside of list? I tried ingredients.parsed.food (nothing returns) and also tried ingredients.parsed['food'] and get a template syntax error Could not parse the remainder: '['food']' from 'ingredients.parsed['food']' and lastly ingredients.parsed[0] since it is the first element in the parsed list, but I get another template syntax error Could not parse the remainder: '[0]' from 'ingredients.parsed[0]'. So ultimately I'm just trying to grab the nutrients dictionary items inside of the food dictionary which seems to be the first element of the parsed dictionary. I'm just not certain how to get to food yet.

Upvotes: 0

Views: 91

Answers (1)

林敬智
林敬智

Reputation: 113

This should work,

ingredients.parsed.0

try it!

Upvotes: 3

Related Questions