How to convert a dictionary to a list of dictionaries

I’m faced with a corner case where some devices are expected to return a list of dictionaries but instead return a single dictionary. This creates an error later on in ansible when a list is expected.
For instance, the device returns the file:
var:

key_1: value_11
key_2: value_21
key_3: value_31

instead of for instance:

var:

  • key_1: value_11
    key_2: value_21
    key_3: value_31
  • key_1: value_12
    key_2: value_22
    key_3: value_32

So the goal is to transform the first var into:
var:

  • key_1: value_11
    key_2: value_21
    key_3: value_31

AFAIK, there is no ansible filters to accomplish that; for instance, ‘list’ does not give the expected result.
Also, we cannot count on the name or number of keys as they may change.
I suppose the solution may revolve around something like that:

  • set_fact:
    list_var: >-
    {% for key, value in var.items() %}
    {{ [{key: value}] }}
    {% endfor %}
    when: >
    (var | type_debug != ‘list’)

This does not give the expected result either.

Any suggestion?

Simply close it in the brackets. For example,

  - debug:
      msg: "{{ [var] }}"

gives

  msg:
    - key_1: value_11
      key_2: value_21
      key_3: value_31

, or

  var2: "{{ [var] + [var] }}"

gives

  var2:
    - key_1: value_11
      key_2: value_21
      key_3: value_31
    - key_1: value_11
      key_2: value_21
      key_3: value_31

So simple!
Nice! :slight_smile:

This works, but if the original var is already a list, you get a list
of a list, which is probably not what the OP wants.
In cases like this I tend to use the "to_array" function of jmespath:

https://jmespath.org/specification.html#to-array

This will always return a list. Example:

many ways to do it conditionally without need for
serializing/deserializing into jaon

var is dict|ternary([var], var)

many ways to do it conditionally without need for
serializing/deserializing into jaon

var is dict|ternary([var], var)

With this I get:

   No test named ''dict''

Shouldn't it be 'mapping' ?

yes, 'mapping' is correct ... this what happens when you respond away
from the computer and don't verify ....