How to convert a dictionary to a list with key=value elements or to a string with key=value elements?

Given an arbitrary dictionary like:

test: one: wan two: too three: tree

How can I convert it to a list like:

`
test:

  • one=wan
  • two=too
  • thee=tree
    `

The end result that I need is actually a string of these list items (“one=one, two=too, three=tree”). I know that I can easily join() a list of items, but if there is an easier way to directly convert the dictionary to a string, that would work too.

Again, I know neither the number of dictionary elements, nor the key names.

A solution that works in version 2.5 would be best…

This should do the trick:

{{ test|dictsort|map(‘join’, ‘=’)|join(', ') }}

In my test, it produces:

ok: [localhost] => {
“msg”: “one=wan, three=tree, two=too”
}

It’s ordered slightly different than your version, and dictsort could help change the sort order, however just a note that python dictionaries in most python versions are unsorted.

I’ll give that a try, thank you.

Is there a way to modify this so that the item to the right of the equal sign was quoted?

So… one=“wan”, two=“too”, three=“tree”

You can always use Jinja template

  - debug: msg="{% for k, v in test.iteritems() %}{{ k }}="{{ v }}"{% if not loop.last %}, {% endif %}{% endfor %}"

That is what I ended up doing, but was curious if there is a ‘filter’ way.