搜索一个字典键并根据另一个列表提取其值。

huangapple go评论90阅读模式
英文:

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 %}

huangapple
  • 本文由 发表于 2023年6月22日 14:55:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定