Get key from a list of dict

Hello,

from the xml module I get a list of dict of interfaces:

TASK [Show result] *****************************************************************************************************
ok: [opnsense] => {
    "iface_current.matches": [
        {
            "lo0": null
        },
        {
            "lan": null
        },
        {
            "wan": null
        },
        {
            "opt1": null
        },
        {
            "opt2": null
        },
        {
            "opt3": null
        }
    ]
}


Any idea how to extract the keys as a list? Best would be without a loop, only with map etc.

The expected result should be:

"iface_current.matches": ["lo0", "lan", "wan", "opt1", "opt2", "opt3"]

Thanks a lot! :slight_smile:

This should be possible using dict2items filter like so:

iface_current_matches: "{{ iface_current.matches | dict2items | map(attribute='key') }}"

… does not work, because iface_current.matches is a list and dict2items expects a dictionary as input…

You can use the map filter (Template Designer Documentation — Jinja Documentation (3.0.x)) to apply dict2items to every element of the list. Then you can use map with the first filter to map the list of lists to a list, and map with attribute='key' to get hold of the keys. Something like this:

iface_current_matches: "{{ iface_current.matches | map('dict2items') | map('first') | map(attribute='key') }}"
3 Likes

ah, works perfect! Thanks a lot :slight_smile:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.