I have a dict in python that is something like the following:
d = {'key1': .98, 'key2': 'some_str',
#...
}
In this dictionary some keys will be mapped to float and others will be mapped to str
In my HTML I am doing something like the following:
html_dict = {
{% for k, v in my_dict.items %}
{{ k }}: "{{ v }}",
{% endfor %}
};
However this approach wraps the floats in quotes as well, which is what I don't want. But if I don't know wrap them in quotes the HTML doesn't understand that they are are string values. I would ideally like something like the following:
html_dict = {
{% for k, v in my_dict.items %}
{% if check_v_is_str %}
{{ k }}: "{{ v }}",
{% else %}
{{ k }}: {{ v }},
{% endif %}
{% endfor %}
};
Don't do this. You are manually trying to replicate a JS data structure, when there already exists a well-defined structure that both Python and JS know about, namely JSON. Use that instead. Convert the dict to JSON in your view, and pass it to the template where it can be output directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With