简体   繁体   English

从2个列表创建字典,在Django模板中使用

[英]Create dictionary from 2 lists, use in django template

I have 2 lists: 我有2个清单:

year_month_day_list = ['2017-02-12', '2017-02-11', '2017-02-10', '2017-02-09']

filename_prefix_list = ['2017-02-12_11-45-59', '2017-02-12_11-35-05', '2017-02-10_11-00-52', '2017-02-11_10-59-23', '2017-02-09_09-12-09']

If I can grab all of the filenames that match their associated ymd: 如果我可以获取与其关联的ymd匹配的所有文件名:

def filter_files(file_list, filter_param):
    return [f for f in file_list
            if f.startswith(filter_param)]

for unique_day in year_month_day_list:
        files_for_day = sorted(filter_files(
            filename_prefix_list, unique_day), reverse=True)

How can I create a dictionary that uses the unique_day as the key and the associated filenames for that day as the values? 如何创建一个使用unique_day作为键并将该日期的关联文件名用作值的字典?

Output should be something like: 输出应该是这样的:

dict = {'2017-02-12': ['2017-02-12_11-45-59', '2017-02-12_11-35-05'], '2017-02-10': ['2017-02-10_11-00-52']}

Then, how can I use those in my template? 然后,如何在模板中使用它们? Something like: 就像是:

<div class="thumbnail-row" id="thumbnail_row">
    <div class="row-date">
        <span>{{ unique_day }}</span>
    </div>
    <div class="">
        <form action="{{ filename_prefix }}/video/" method="post">
            {% csrf_token %}
            <input type="image" name="filename_prefix" value="{{ filename_prefix }}" src="{{ MEDIA_URL}}thumbnails/2017/02/{{ filename_prefix }}.jpg">
        </form>
    </div>
</div>

You can use itertools.groupby to group the list items by their dates. 您可以使用itertools.groupby按日期对列表项进行分组。 The date can be sliced from the datetime strings and used as the grouping key. 可以从日期时间字符串中分割日期,并将其用作分组键。 You can drop sorted if the datetime strings are already clustered by dates: 如果datetime字符串已按日期聚类,则可以删除sorted

from itertools import groupby
from pprint import pprint

filename_prefix_list = ['2017-02-12_11-45-59', '2017-02-12_11-35-05', '2017-02-10_11-00-52', '2017-02-11_10-59-23', '2017-02-09_09-12-09']

dct = {k: list(g) for k, g in groupby(sorted(filename_prefix_list), lambda x: x[:10])}
pprint(dct)
# {'2017-02-09': ['2017-02-09_09-12-09'],
#  '2017-02-10': ['2017-02-10_11-00-52'],
#  '2017-02-11': ['2017-02-11_10-59-23'],
#  '2017-02-12': ['2017-02-12_11-35-05', '2017-02-12_11-45-59']}

To use the dictionary in your template simply pass it to the current context via your view function, and get its key-value pairs by calling its items method using {% for k, v in dct.items %} . 要在模板中使用字典,只需通过view函数将其传递到当前上下文,并通过使用{% for k, v in dct.items %}调用其items方法来获取其键值对。

More generally: 更普遍:

{% for k, v in dct.items %}
     {% for dt in v %}
     <!- your html -->
     {% endfor %}
{% endfor %}

For converting the lists into the desired format dict , you may use collections.defaultdict as: 要将列表转换为所需的格式dict ,可以将collections.defaultdict用作:

from collections import defaultdict

year_month_day_list = ['2017-02-12', '2017-02-11', '2017-02-10', '2017-02-09']
filename_prefix_list = ['2017-02-12_11-45-59', '2017-02-12_11-35-05', '2017-02-10_11-00-52', '2017-02-11_10-59-23', '2017-02-09_09-12-09']

my_dict = defaultdict(list)
for year_month_day in year_month_day_list:
    for filename_prefix in filename_prefix_list:
        if filename_prefix.startswith(year_month_day):
            my_dict[year_month_day].append(filename_prefix)

where value hold by my_dict will be: my_dict保留的my_dict将为:

{
    '2017-02-09': ['2017-02-09_09-12-09'], 
    '2017-02-10': ['2017-02-10_11-00-52'], 
    '2017-02-12': ['2017-02-12_11-45-59', '2017-02-12_11-35-05'],        
    '2017-02-11': ['2017-02-11_10-59-23']
}

For accessing dict objects in Django's template, you will have to do something like: 要访问Django模板中的dict对象,您将必须执行以下操作:

{% for key, values in my_dict.items %} 
    {{key}}
    {% for value in values %}
        {{value}}
    {% endfor %} 
{% endfor %}

For more details, refer: How to access dictionary element in django template? 有关更多详细信息,请参阅: 如何在Django模板中访问字典元素?


Note: Do not use dict as variable name since dict is an in-built type in Python. 注意:请勿将dict用作变量名,因为dict是Python中的内置类型。

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

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