【问题标题】:how to create dict with keys from list and static values in jinja如何使用 jinja 中的列表和静态值中的键创建 dict
【发布时间】:2020-11-12 20:57:04
【问题描述】:

我有清单

a = [1,2,3]

还有一个

b = ['a','b']

如何制作这样的字典:

{
1: ['a','b'],
2: ['a','b'],
3: ['a','b']
}

表达喜欢

dict(a,map(b)) is not working

【问题讨论】:

  • 一开始就这样做可能不是最好的主意——这种模式在 C++ 等“隐式复制无处不在”的语言中效果更好。虽然您可以在 Python 中手动进行复制,但 Python 中的复制功能远不如该语言可靠或集成到该语言中。
  • {item: b for item in a}
  • (这里的副本是您必须制作的 b 的副本,因为 {item: b for item in a} 就像 Alexander Lekontsev 建议的那样会生成一个字典,其中所有值都是对同一个列表对象的引用。)

标签: python dictionary templates jinja2


【解决方案1】:

Jinja 模板也有 for 循环,你应该尝试做类似的事情:

{% for nb in a %}
  {{ nb }}: {{ a[nb-1] }}
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 2022-08-18
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    相关资源
    最近更新 更多