简体   繁体   English

如何在 Django 模板中使用列表迭代字典作为值?

[英]How do I iterate dictionary with lists as values in Django template?

I have a dictionary with lists as values (truncated to give you an example):我有一个列表作为值的字典(截断给你一个例子):

imageFiles:图像文件:

for prop in context['results'][0]:
        imageFolderPath ='./media/uploaded/prop_images/' + prop.property_ID
        if os.path.isdir(imageFolderPath):
            imageFileList[prop.property_ID] = [f for f in listdir(imageFolderPath) if isfile(join(imageFolderPath, f))]
    

context['imageFiles'] = [imageFileList]

Here is what shows up when I print it directly in the template:这是我直接在模板中打印时显示的内容:

[{'R01': ['02secparking27.jpg', '10-2017-ff-detail-1200x627.jpg', '1200x820.jpg', '12539233_web1_180704-VMS-parking-lot.jpg', '16.12.01-519196006.jpg',], 
'R02': ['asdasd.jpg','12131asad.jpg','asdasdasd.jpg']}]

In the template, I am trying to access the image names by iterating but I am getting no values.在模板中,我试图通过迭代来访问图像名称,但我没有得到任何值。

{% for keys,values in imageFiles %}
   {% for x in values %}
     <p>  {{X}}  </p>
   {% endfor %}
{% endfor %}

getting error出错

"Need 2 values to unpack in for loop; got 9." “需要 2 个值才能在 for 循环中解压;得到 9 个。”

I also tried imageFiles.items as suggested in other posts and it doesn't seem to work.我还按照其他帖子中的建议尝试了 imageFiles.items ,但它似乎不起作用。

What am I doing wrong?我究竟做错了什么? Wracking my brain here.在这里绞尽脑汁。

So, you're passing in:所以,你正在传递:

context['imageFiles'] = [imageFileList]

Which is pretty confusing, for no good reason.这很令人困惑,没有充分的理由。 What you're calling imageFileList isn't a list, but a dictionary.你所说的imageFileList不是一个列表,而是一个字典。 Then, what you pass into the template is a list with a single element, namely that dictionary.然后,您传递给模板的是一个具有单个元素的列表,即该字典。

Fix: Pass in the dictionary (it would be even nicer if you changed the name of imageFileList to something less confusing):修复:传入字典(如果您将imageFileList的名称更改为不那么令人困惑的名称会更好):

context['imageFiles'] = imageFileList

In your template:在您的模板中:

{% for key, value in imageFiles.items %} 
    {% for x in values %}
        <p>  {{x}}  </p>
    {% endfor %}
{% endfor %}

Assumed假定

dct = your input dictionary

code:代码:

[value for keys, values in dct.items() for value in values]

will give you the below list of file names:将为您提供以下文件名列表:

['02secparking27.jpg',
 '10-2017-ff-detail-1200x627.jpg',
 '1200x820.jpg',
 '12539233_web1_180704-VMS-parking-lot.jpg',
 '16.12.01-519196006.jpg',
 'asdasd.jpg',
 '12131asad.jpg',
 'asdasdasd.jpg']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM