3

Suppose I've a dict like:

dic = {'1': 'string', 1 :'integer'}

When I pass it to a django template and try to access dic.1 then it always returns 'string'.

If I remove the key '1', then dic.1 returns 'integer'.

I know I can use a custom tag for this, something like:

from django import template
register = template.Library()
@register.filter
def get_key(value, arg):
    return value.get(arg, None)

Then {{ dic|get_key:1 }} works fine.

But, is there a way to directly access the integer/float keys without using a custom tag?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • 4
    Why do you have a dict with 2 keys sharing the same name? That's a really bad idea to begin with. If I understand dict's correctly, then each time you make a key with a name already used, then you're overwriting the old data in the key – Zamphatta Jul 26 '13 at 15:15
  • @Zamphatta No you don't understand dicts correctly, `'1'` and `1` are two different keys. – Ashwini Chaudhary Jul 26 '13 at 15:44
  • 1
    There is a ugliest way: {% for k, v in dic.items %}{% ifequal k '1' %}{% endifequal %}{% endfor %}. But I would really avoid that. But reading that (http://stackoverflow.com/questions/2970244/django-templates-value-of-dictionary-key-with-a-space-in-it) I don't think there is a better solution than template tags. – Ricola3D Jul 26 '13 at 16:01
  • @Ricola3D Hmmm, I think I should start using jinja-templates which allows `dic[1]` syntax inside tags. – Ashwini Chaudhary Jul 26 '13 at 16:09
  • Can you explain why you want to do that? It sounds like bad idea. You are making your code much harder to read and maintain this way. – Tomasz Wysocki Aug 11 '13 at 19:14
  • @Ricola3D I found out that your answer is (also) helpful when the dict's key is an int. It's non-trivial to access the dict's value from the template when the key is an int – Jay Oct 17 '17 at 14:11

1 Answers1

3

Refer to the answer provided for the question on the topic of Dictionary access speed comparison with integer key against string key. Python (CPython) will always first try to find the string-based key before attempting to find any alternative.

You might have a very good reason to mix similar string keys with integer keys, but I would recommend avoiding this technique or type-casting the integers to strings to eliminate the inability to directly reference the key values.

Community
  • 1
  • 1
Joseph Paetz
  • 876
  • 1
  • 7
  • 12