How to construct a csv string from a dictionary

14 views
Skip to first unread message

The Gripmaster

unread,
Apr 6, 2017, 7:31:12 AM4/6/17
to Ansible Project
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

Matt Martz

unread,
Apr 6, 2017, 11:10:22 AM4/6/17
to ansible...@googlegroups.com
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(',') }}

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-project+unsubscribe@googlegroups.com.
To post to this group, send email to ansible-project@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/a12df541-e10f-4aad-a486-18a277c1f358%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Matt Martz
@sivel
sivel.net
Reply all
Reply to author
Forward
0 new messages