英文:
Search a dictionary key and fetch it's values based on another list
问题
我有一个类似的帐户ID列表,如下:account_id_list = [1,2,3,4,5,6,7]
我有一个类似的字典,如下:tag_dict = {1: {"a": "b", "y": "z"}, 2: {"a": "b", "y": "z"}, 3: {"a": "b", "y": "z"}}
我想在jinja2中执行一个操作,以便我可以对account_id_list进行循环,并使用值3作为参考,然后能够获取tag_dict中的键,即3,并获取其值。
我对jinja相当新手,尝试在for循环内部使用for循环,但运行时间很长,我想知道是否有更简单的方法。
英文:
I have a list like account_id_list = [1,2,3,4,5,6,7]
I have a dictionary like tag_dict = [1:{"a"= "b", "y"= "z"}, 2:{"a"= "b", "y"= "z"}, 3:{"a"= "b", "y"= "z"}]
I want to perform an operation in jinja2 such that i should be able to do a for loop on account_id_list and using the value 3 as a reference i should be able to fetch the key i.e 3 in tag_dict and fetch its values.
I am pretty new to jinga and i tried to use a for loop inside a for loop but it's running for a long time and i want to know if there is a easy way of doing it.
答案1
得分: 1
tag_dict 看起来格式不正确。你是不是想要这样?
tag_dict = {1: {"a": "b", "y": "z"}, 2: {"a": "b", "y": "z"}, 3: {"a": "b", "y": "z"}}
这个应该适用于你:
{%- set account_id_list = [1,2,3,4,5,6,7] -%}
{%- set tag_dict = {1: {"a": "b", "y": "z"}, 2: {"a": "b", "y": "z"}, 3: {"a": "b", "y": "z"}} -%}
{% for value in account_id_list %}
{{ tag_dict[value] }}
{% endfor %}
英文:
Your tag_dict looks malformed. Did you mean this?
tag_dict = {1:{"a":"b","y":"z"},2:{"a":"b","y":"z"},3:{"a":"b","y":"z"}}
This should work for you:
{%- set account_id_list = [1,2,3,4,5,6,7] -%}
{%- set tag_dict = {1:{"a":"b","y":"z"},2:{"a":"b","y":"z"},3:{"a":"b","y":"z"}} -%}
{% for value in account_id_list %}
{{ tag_dict[value] }}
{% endfor %}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论