Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if key exists in a Python dict in Jinja2 templates

I have a python dictionary:

settings = {
   "foo" : "baz",
   "hello" : "world"
}

This variable settings is then available in the Jinja2 template.

I want to check if a key myProperty exists in the settings dict within my template, and if so take some action:

{% if settings.hasKey(myProperty) %}
   takeSomeAction();
{% endif %}

What is the equivalent of hasKey that I can use?

like image 870
Amal Antony Avatar asked Jan 02 '15 09:01

Amal Antony


People also ask

How do you check if a key exists in a Python dict?

Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.

How do you check if a key exists or not?

Method 3: Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

How do you check if a key exists in a list of dictionaries?

You can check if a key exists in a dictionary using the keys() method and IN operator. The keys() method will return a list of keys available in the dictionary and IF , IN statement will check if the passed key is available in the list. If the key exists, it returns True else, it returns False .

How do you check if something is in a dict?

Check if Variable is a Dictionary with is Operator We can use the is operator with the result of a type() call with a variable and the dict class. It will output True only if the type() points to the same memory location as the dict class. Otherwise, it will output False .


3 Answers

Like Mihai and karelv have noted, this works:

{% if 'blabla' in item %}
  ...
{% endif %}

I get a 'dict object' has no attribute 'blabla' if I use {% if item.blabla %} and item does not contain a blabla key

like image 57
tshalif Avatar answered Oct 18 '22 03:10

tshalif


You can test for key definition this way:

{% if settings.property is defined %}

#...
{% endif %}
like image 30
ma3oun Avatar answered Oct 18 '22 04:10

ma3oun


This works fine doesn't work in cases involving dictionaries. In those cases, please see the answer by tshalif. Otherwise, with SaltStack (for example), you will get this error:

Unable to manage file: Jinja variable 'dict object' has no attribute '[attributeName]'

if you use this approach:

{% if settings.myProperty %}

note:
Will also skip, if settings.myProperty exists, but is evaluated as False (e.g. settings.myProperty = 0).

like image 15
Mihai Zamfir Avatar answered Oct 18 '22 03:10

Mihai Zamfir