4
a = {'key1':'value1', 'key2':'value2', 'key3':'value3'...}

This dictionary is being sent to my django template. How can I get value1?

Note: I don't know key1, as it is dynamically generated.

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
sundeepg
  • 432
  • 2
  • 8
  • 18
  • 2
    Dictionaries aren't ordered, so there isn't a 'first' value. You can get all the values in a list with `a.values`, or get the first of this list (not necessarily `value1`) with `a.values.0`. – Ben May 27 '16 at 07:54

1 Answers1

1

Use first filter with dict.values method:

{{ a.values|first }}

But remember: dict is unordered. Of course You can use OrderedDict

For OrderedDict use make_list filter :

{{ a.values|make_list|first }}
Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
  • I didn't understand why you used make_list.. But it worked without that... {{ a.values | first }} – sundeepg May 30 '16 at 06:27
  • 1
    Django is smarter than I thought. `dict.values` return a `dict_values` class object that does not support indexing. Fixed. – Tomasz Jakub Rup May 30 '16 at 06:49
  • `first` does not work for me on an `OrderedDict`. Returns a `TypeError` `odict_values' object does not support indexing`? – Anupam Jul 18 '18 at 17:07
  • @Anupam use `make_list` filter first – Tomasz Jakub Rup Jul 19 '18 at 18:49
  • 1
    @TomaszJakubRup yeah I had picked that up from the edit history and did try it earlier :) That didnt work either. It strangely converted everything into a list of characters `['o', 'd', 'i', 'c', 't', '_', 'v', 'a', 'l', 'u', 'e', 's', '(', '[', '0', ',', ' ', '0', ',', ' ', '0', ']', ')']` So `first` returned `o` – Anupam Jul 21 '18 at 10:35
  • FYI: I just ended up creating a template tag to lookup the first value using the key like in [this answer](https://stackoverflow.com/a/8000091/1526703) (I do know the key beforehand - unlike OP's case) – Anupam Jul 22 '18 at 12:48