Syntax_Error
Syntax_Error

Reputation: 6220

Javascript iterate over python dict

I am creating a python dictionary and passing it over to javascript.

var students = {{myStudents}}

when generated becomes

var students = [(u'Mark', u'b7'), (u'Phillipe', u'a67'), (u'John', u'a1')]

Now I need to loop over the names (Mark, Philippe, etc...) and populate a dropdown list.

My problem, how can I access the key/value separately. Ultimately I could pass both lists separately, but I want to check if their is another non-bruteforce way.

Upvotes: 0

Views: 2535

Answers (4)

Omer
Omer

Reputation: 126

I tried the answers here and it didn't work for me. I figured out that all I had to do is to parse the JSON data. I thought that sharing this solution might be helpful for others: In the python file:

import json
json_data = json.dumps(your_dict)

pass the json_data to your Javascript file. In your Javascript file:

var keys = JSON.parse(json_data);
for (var key in keys) {

}

Upvotes: 0

EZE ARINZE
EZE ARINZE

Reputation: 13

Like @jsfan pointed out, python dictionary would render as follows: {u'students': {u'Mark': u'b7', u'Phillipe': u'a67', u'John': u'a1'}}. To iterate over the dictionary you use,

  for (x in students) {
    students[x]
 }

But if you wish to get value for a particular key, for example the value for key 'Mark', you use:

for (x in students)
 {
    students[x]['Mark']
}

Upvotes: 0

Selcuk
Selcuk

Reputation: 59184

If you really have a dict in myStudents, you could write your template as:

var students = {{% for key, value in myStudents %}{"{{ key }}": "{{ value }}"},{% endfor %}}

which will become

var students = {"Mark": "b7", "Philippe": "a67", ...}

in your HTML source. You can then iterate it in Javascript using the following:

for(var key in students) {
  var value = students[key];
  ...
}

Upvotes: 1

jsfan
jsfan

Reputation: 1373

Before passing the variable to Javascript, you want to

import json
json_var = json.dumps(var)

and then pass json_var instead of var to the Javascript.

In Javascript you then iterate over it as

for (k in students) {
}

using k to get the names and students[k] to get the value associated with the name.

If you want to stick with your list of tuples, use the value students[k][0] in the loop for the names and students[k][1] for the second value in the tuple.

Upvotes: 1

Related Questions