How to construct a csv string from a dictionary

I have a dictionary like this

customers: abc: id: 1 status: active def: id: 2 status: inactive ghi: id: 3 status: active jkl: id: 4 status: active

What’s the best way to construct a string like below of the active customers only?

abc,ghi,jkl

Something like the following would do it, with your current data structure.

{% for k, v in customers|dictsort if v.status == ‘active’ %}{{ k }}{% if not loop.last %},{% endif %}{% endfor %}

If you rewrote your data structure to look like:

customers:

  • name: abc:
    id: 1
    status: active

Then it could be:

{{ customers|selectattr(‘status’, ‘match’, ‘active’)|map(attribute=‘name’)|join(‘,’) }}