I am trying to check if a value exists inside a list with dictionaries. I use flask 1.0.2. See example below:
person_list_dict = [
{
"name": "John Doe",
"email": "[email protected]",
"rol": "admin"
},
{
"name": "John Smith",
"email": "[email protected]",
"rol": "user"
}
]
I found two ways to solve this problem, can you tell me which is better?:
<pre>{% if "admin" in person_list_dict|map(attribute="rol") %}YES{% else %}NOPE{% endif %}</pre>
# return YES (john doe) and NOPE (john smith)
Flask code:
@app.template_filter("is_in_list_dict")
def is_any(search="", list_dict=None, dict_key=""):
if any(search in element[dict_key] for element in list_dict):
return True
return False
Template code:
<pre>{% if "admin"|is_in_list_dict(person_list_dict, "rol") %} YES {% else %} NOPE {% endif %}</pre>
# return YES (john doe) and NOPE (john smith)
Thanks :-).
If possible, I would move this logic to the python part of the script before rendering it in Jinja. Because, as stated in the Jinja documentation: "Without a doubt you should try to remove as much logic from templates as possible."
any([person['role'] == 'admin' for person in person_dict_list])
is a lot easier to follow at first glance than the other 2 options.
If that's not an option, I would probably use the first, build in function, because I think it's less prone to errors in edge cases as your own solution, and is about 6x less code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With