0

In the django documentation it says that . notation will do a lookup in the following order

#Dictionary lookup. Example: 
foo["bar"]
#Attribute lookup. Example: 
foo.bar
#List-index lookup. Example: 
foo[bar]

In my project I have a dictionary:

foo = {'ba-r':'...}

But using . notation causes an error, which appears to be because the entire 'foo.ba-r' is a variable as described in the documentation here.

foo.ba-r

Is there any way to properly access the 'ba-r' key of my dictionary?

grrrrrr
  • 1,395
  • 12
  • 29
  • Is there a reason why you can't use foo["ba-r"]? – Carlos Perea Jun 21 '16 at 16:37
  • 2
    Possible duplicate of [How do I access dictionary keys that contain hyphens from within a Django template?](http://stackoverflow.com/questions/8252387/how-do-i-access-dictionary-keys-that-contain-hyphens-from-within-a-django-templa) and [dict keys with spaces in Django templates](http://stackoverflow.com/questions/1906129/dict-keys-with-spaces-in-django-templates) – solarissmoke Jun 21 '16 at 16:39

1 Answers1

4

As you already discovered, you cannot access such a key in your template without raising a ParseError. You can use a custom filter for instance:

from django import template

register = template.Library()

@register.filter
def get_key_value(some_dict, key):
   return some_dict.get(key, '')

And use it like

{{ entry | get_key_value:"ba-r" }} 

Or change your dictionnary structure so it does not contain such keys!

Seb D.
  • 5,046
  • 1
  • 28
  • 36