0

I have 2 dictionaries dict1 and dict2. I'm trying to get the value by the dict1 key to the dict2 key but it getting nothing, is there any way to get the value of dict2 by the dict1 key? always both dictionaries will be the same length?

dict1 = {0:[1,2,3],1:[4,5,6]}
dict2 = {0:'data1',1:'data2'}

{% for key, value in dict1.items %}
 {{dict2.key}}

{% endfor %}
Abhi
  • 67
  • 7

1 Answers1

1

You need a custom template tag:

myapp/templatetags/myapp_extras.py: source 1, source2

from django.template.defaulttags import register

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

template.html

{% extends 'base.html' %}
{% load myapp_extras %}

{% block content %}
    {% for key, value in dict1.items %}
        <td>Value 1: {{ value }}</td>
        <td>Value 2: {{ dict2|get_item:key }}</td>
        <br>
    {% endfor %}
{% endblock content%}   

settings.py: source

TEMPLATE_LOADERS = (
    'django.template.loaders.app_directories.load_template_source',
)

But, since both dictionaries have the same length and same keys, why not have both of them nested?

data = {
    0 : {'list':[1,2,3], 'data':'data1'},
    1 : {'list':[4,5,6], 'data':'data2'}
}


{% for key, value in data.items %}
    {{value.list}}
    {{value.data}}
    <br>
{% endfor %}
Niko
  • 3,012
  • 2
  • 8
  • 14