Django, Response using List of Dict

django display dictionary in template
httpresponse django
django dictionary example
django template access dictionary by key
django template loop through list of dictionaries
python dictionary
django template access dictionary key variable
django template nested dictionary

I'm looking to be able for response using list of dict like following

bio_dict = [{'subject' : 'Name', 'value' : 'MyName'},\
    {'subject' : 'Birth Date', 'value' : '1998-1-1'},\
    {'subject' : 'Sex', 'value' : 'M'}]

def index(request):
    response = { bio_dict['subject'] : bio_dict['value'] }
    return render(request, 'page.html', response)

but that response return:

TypeError: list indices must be integers or slices, not str

Using python 3.6 and django 1.11

The error comes from the fact that you call

bio_dict['subject'] and bio_dict['value']

but bio_dict is a list. This is the syntax to access a dictionary not a list.

Now, in order to have an output like you wanted, you could use dict comprehension like so,

response = {item['subject']:item['value'] for item in bio_dict} 

that way you have a similar syntax of what you tried, but now you iterate on each dict in bio_dict and accessing them instead.

How to List Items In A Django Dictionary in Templates, This quick tutorial covers how to iterate over a Django dictionary in templates. Free code First, in your view, make sure that you're returning a rendered response that looks something like this: view raw render.py hosted with ❤ by GitHub. Here's a quick to tutorial on how to iterate over a dictionary in a Django template. I get asked this quite a lot so I figured I'd put it online in case anybody is Googling it. Dictionary Items. First, in your view, make sure that you're returning a rendered response that looks something like this:

So if you look at bio_dict, its a list, and as the exception says, list indices must be integers or slices.

By doing - bio_dict['subject'] you are essentially passing a string as list index.

You will first need to access the list like -

bio_dict[0] and by doing this, you will be able to access the dictionaries that the list contains.

And since there are three dicts int the list, bio_dict[0] will give you the first dict which is -

{'subject' : 'Name', 'value' : 'MyName'

and bio_dict[1] will get you the second dict which is -

{'subject' : 'Birth Date', 'value' : '1998-1-1'}

and so on.

You can access the dict elements by -

bio_dict[0]['subject']

and so on.

Depending on the use case, you could use a loop like -

for dict in list:
    for key, value in dict.iteritems():
    # do something with key or value

Request and response objects | Django documentation, Django uses request and response objects to pass state through the system. item), where item is one element of the list, using the same logic as QueryDict. Django uses request and response objects to pass state through the system. When a page is requested, Django creates an HttpRequest object that contains metadata about the request. Then Django loads the appropriate view, passing the HttpRequest as the first argument to the view function. Each view is responsible for returning an HttpResponse object.

As already mentioned, bio_dict is a list, not a dictionary. If you want to create a context dict response for your view, you can do it like the following:

bio_dict = [{'subject' : 'Name', 'value' : 'MyName'},\
{'subject' : 'Birth Date', 'value' : '1998-1-1'},\
{'subject' : 'Sex', 'value' : 'M'}]
def index(request):
   response = {}
   for item in bio_dict:
        # populate response = {}
        response[item['subject']] = item['value']
   return render(request, 'page.html', response)

#16335 (Document why you cannot iterate defaultdict in templates , I am unable to iterate a defaultdict using a for loop in a template. dictionary = defaultdict(list) dictionary['foo'].append('bar') {% for key, value in dictionary.items .7/site-packages/django/core/handlers/wsgi.py", line 206, in __call__ response​  This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using the value of this property. """ template = self. resolve_template (self. template_name) context = self. resolve_context (self. context_data) content = template. render (context, self. _request) return content

try to just pass dict instead full key and values . See Variables and lookups

bio_dict = {
              'name' : 'MyName', 
              'birth_date': '1998-1-1',
              'sex' : 'M'
           }

def index(request):
    response = { bio_dict: 'bio_dict' }
    return render(request, 'page.html', response)

and in your template page.html , to render the value in html template use:

{% for my_key, my_value in bio_dict.items %}

  <p> {{ my_key }} : {{ my_value }} </p>

{% endfor %}

Handling missing keys in Python dictionaries, Python | Subtraction of dictionaries · Get() method for dictionaries in Python · Python | Merging two Dictionaries · Python | Sum list of dictionaries with same key​  Using TemplateResponse and SimpleTemplateResponse ¶ A TemplateResponse object can be used anywhere that a normal django.http.HttpResponse can be used. It can also be used as an alternative to calling render(). For example, the following view returns a TemplateResponse with a template and a context containing a queryset:

20. Dictionaries, Python uses complex algorithms, designed for very fast access, to determine where the Another way to create a dictionary is to provide a list of key:value pairs using the Give the Python interpreter's response to each of the following from a  This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using the value of this property. """ template = self. resolve_template (self. template_name) context = self. resolve_context (self. context_data) content = template. render (context, self. _request) return content

QueryDict - django - Python documentation, QueryDict , a dictionary-like class customized to deal with multiple values for the same GET will be immutable when accessed in a normal request/response cycle. Sets the given key to [value] (a Python list whose single element is value ). Django JsonResponse. JsonResponse is an HttpResponse subclass that helps to create a JSON-encoded response. Its default Content-Type header is set to application/json. The first parameter, data, should be a dict instance. If the safe parameter is set to False, any object can be passed for serialization; otherwise only dict instances are allowed.

Python Tutorial: Dictionaries, At the end of this chapter, we will demonstrate how a dictionary can be turned into one list, containing (key,value)-tuples or two lists, i.e. one with the keys and one  The following are code examples for showing how to use django.http.QueryDict().They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Comments
  • bio_dict is a list, not a dict
  • Why is your bio_dict not just {'Name': 'MyName', 'Birth Date': '1998...}?
  • Because i want bio_dict as a table, for example an additional 'attribue' tag,
  • Accessing dict one by one is actually far from optimal.
  • @scharette no doubt about that. This is just to explain how they can be accessed.
  • Well you clearly imply that he should be using an index based solution to access the list, which is bad practice.
  • I do not understand how I am implying that meanwhile all I am doing is trying to make him understand how we can access lists and dictionaries. Added a for loop example as well.
  • This page.html is like what i needed but with bio_dict: 'bio_dict',I got TypeError: unhashable type: 'list'
  • @dika_saja , The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. i´ve EDIT my answer to adress what you need. have a try.