# How to construct a csv string from a dictionary

**URL:** <https://forum.ansible.com/t/how-to-construct-a-csv-string-from-a-dictionary/24155>\
**Category:** Ansible Project\
**Created:** [April 6, 2017, 8:10am UTC](https://forum.ansible.com/t/how-to-construct-a-csv-string-from-a-dictionary/24155 "2017-04-06T08:10:04Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![The\_Gripmaster](https://avatars.discourse-cdn.com/v4/letter/t/b38774/32.png) [@The\_Gripmaster](https://forum.ansible.com/u/The_Gripmaster)\
**Post date:** [April 6, 2017, 8:10am UTC](https://forum.ansible.com/t/how-to-construct-a-csv-string-from-a-dictionary/24155/1 "2017-04-06T08:10:04Z")

</div>

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`

---

<div class="post-metadata">

**Author:** ![sivel](https://sea1.discourse-cdn.com/ansible/user_avatar/forum.ansible.com/sivel/32/1198_2.png) [@sivel](https://forum.ansible.com/u/sivel)\
**Post date:** [April 6, 2017, 3:09pm UTC](https://forum.ansible.com/t/how-to-construct-a-csv-string-from-a-dictionary/24155/2 "2017-04-06T15:09:23Z")

</div>

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(‘,’) }}
